okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b2de2641f
main
1#include "llama-vocab.h" 2 3#include "ggml.h" 4#include "gguf.h" 5#include "llama-impl.h" 6#include "llama-model-loader.h" 7 8#include "unicode.h" 9 10#include <algorithm> 11#include <cassert> 12#include <cctype> 13#include <cfloat> 14#include <cmath> 15#include <cstdarg> 16#include <cstring> 17#include <cstdlib> 18#include <forward_list> 19#include <limits> 20#include <map> 21#include <queue> 22#include <set> 23#include <unordered_map> 24 25// 26// helpers 27// 28 29struct naive_trie { 30naive_trie () :has_value (false),value (0 ) { 31 } 32void insert (const char * key ,size_t len ,int32_t value = 0 ) { 33if (len == 0 ) { 34this -> has_value = true; 35this -> value = value ; 36return ; 37 } 38char c = key [0 ]; 39auto res = children .find (c ); 40if (res != children .end ()) { 41res -> second .insert (key + 1 ,len - 1 ,value ); 42 }else { 43auto res = children .insert (std::make_pair (c ,naive_trie ())); 44res .first -> second .insert (key + 1 ,len - 1 ,value ); 45 } 46 } 47 std::pair < const char * ,size_t > get_longest_prefix (const char * key ,size_t len ,size_t offset = 0 )const { 48if (len == 0 || offset == len ) { 49return std::make_pair (key ,offset ); 50 } 51char c = key [offset ]; 52auto res = children .find (c ); 53if (res != children .end ()) { 54return res -> second .get_longest_prefix (key ,len ,offset + 1 ); 55 } 56 57return std::make_pair (key ,offset ); 58 } 59const struct naive_trie * traverse (const char c )const { 60auto res = children .find (c ); 61if (res != children .end ()) { 62return & res -> second ; 63 } 64 65return NULL ; 66 } 67 std::map < char ,struct naive_trie > children ; 68bool has_value ; 69llama_token value ; 70}; 71 72// 73// tokenizers 74// 75 76struct llm_tokenizer { 77llm_tokenizer () {} 78virtual ~llm_tokenizer ()= default ; 79}; 80 81struct llm_symbol { 82using index = int ; 83index prev ; 84index next ; 85const char * text ; 86size_t n ; 87}; 88 89static_assert(std::is_trivially_copyable < llm_symbol > ::value ,"llm_symbol is not trivially copyable" ); 90 91// 92// SPM tokenizer 93// original implementation: 94// https://github.com/ggml-org/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4 95// 96 97struct llm_bigram_spm { 98struct comparator { 99bool operator()(llm_bigram_spm & l ,llm_bigram_spm & r ) { 100return (l .score < r .score )|| (l .score == r .score && l .left > r .left ); 101 } 102 }; 103using queue_storage = std::vector < llm_bigram_spm > ; 104using queue = std::priority_queue < llm_bigram_spm ,queue_storage ,comparator > ; 105 llm_symbol::index left ; 106 llm_symbol::index right ; 107float score ; 108size_t size ; 109}; 110 111struct llm_tokenizer_spm :llm_tokenizer { 112llm_tokenizer_spm (const llama_vocab & /*vocab*/ ) {} 113}; 114 115struct llm_tokenizer_spm_session { 116llm_tokenizer_spm_session (const llama_vocab & vocab ) :vocab (vocab ) {} 117 118void tokenize (const std::string & text , std::vector < llama_token > & output ) { 119// split string into utf8 chars 120int index = 0 ; 121size_t offs = 0 ; 122while (offs < text .size ()) { 123llm_symbol sym ; 124size_t len = unicode_len_utf8 (text [offs ]); 125sym .text = text .c_str ()+ offs ; 126sym .n = std::min (len ,text .size ()- offs ); 127offs += sym .n ; 128sym .prev = index - 1 ; 129sym .next = offs == text .size () ?-1 :index + 1 ; 130index ++ ; 131symbols .emplace_back (sym ); 132 } 133 134// seed the work queue with all possible 2-character tokens. 135for (int i = 1 ;i < (int )symbols .size ();++ i ) { 136try_add_bigram (i - 1 ,i ); 137 } 138 139// keep substituting the highest frequency pairs for as long as we can. 140while (!work_queue .empty ()) { 141auto bigram = work_queue .top (); 142work_queue .pop (); 143 144auto & left_sym = symbols [bigram .left ]; 145auto & right_sym = symbols [bigram .right ]; 146 147// if one of the symbols already got merged, skip it. 148if (left_sym .n == 0 || right_sym .n == 0 || 149left_sym .n + right_sym .n != bigram .size ) { 150continue ; 151 } 152 153// merge the right sym into the left one 154left_sym .n += right_sym .n ; 155right_sym .n = 0 ; 156 157//LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size); 158 159// remove the right sym from the chain 160left_sym .next = right_sym .next ; 161if (right_sym .next >=0 ) { 162symbols [right_sym .next ].prev = bigram .left ; 163 } 164 165// find more substitutions 166try_add_bigram (left_sym .prev ,bigram .left ); 167try_add_bigram (bigram .left ,left_sym .next ); 168 } 169 170for (int i = 0 ;i != -1 ;i = symbols [i ].next ) { 171auto & symbol = symbols [i ]; 172resegment (symbol ,output ); 173 } 174 } 175 176private : 177void resegment (llm_symbol & symbol , std::vector < llama_token > & output ) { 178auto text = std::string (symbol .text ,symbol .n ); 179auto token = vocab .text_to_token (text ); 180 181// Do we need to support is_unused? 182if (token != LLAMA_TOKEN_NULL ) { 183output .push_back (token ); 184return ; 185 } 186 187const auto p = rev_merge .find (text ); 188 189if (p == rev_merge .end ()) { 190// output any symbols that did not form tokens as bytes. 191output .reserve (output .size ()+ symbol .n ); 192for (int j = 0 ;j < (int )symbol .n ;++ j ) { 193llama_token id = vocab .byte_to_token (symbol .text [j ]); 194output .push_back (id ); 195 } 196return ; 197 } 198 199resegment (symbols [p -> second .first ],output ); 200resegment (symbols [p -> second .second ],output ); 201 } 202 203void try_add_bigram (int left ,int right ) { 204if (left == -1 || right == -1 ) { 205return ; 206 } 207const std::string text = std::string (symbols [left ].text ,symbols [left ].n + symbols [right ].n ); 208auto token = vocab .text_to_token (text ); 209 210if (token == LLAMA_TOKEN_NULL ) { 211return ; 212 } 213 214if (static_cast < uint32_t > (token ) >=vocab .n_tokens ()) { 215return ; 216 } 217 218const auto & tok_data = vocab .get_token_data (token ); 219 220llm_bigram_spm bigram ; 221bigram .left = left ; 222bigram .right = right ; 223bigram .score = tok_data .score ; 224bigram .size = text .size (); 225 226work_queue .push (bigram ); 227 228// Do we need to support is_unused? 229rev_merge [text ]= std::make_pair (left ,right ); 230 } 231 232const llama_vocab & vocab ; 233// currently unused 234// const llm_tokenizer_spm * spm_tokenizer; 235 236 std::vector < llm_symbol > symbols ; 237 llm_bigram_spm::queue work_queue ; 238 std::map < std::string , std::pair < int ,int >> rev_merge ; 239}; 240 241// 242// BPE tokenizer 243// adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License] 244// tried to simplify unicode stuff, so most likely does not work 100% correctly! 245// 246 247// TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused 248 249template < typename T ,typename Container = std::vector < T > ,typename Compare = std::less < typename Container ::value_type >> 250class llama_priority_queue :public std::priority_queue < T ,Container ,Compare > { 251public : 252using std::priority_queue < T ,Container ,Compare > ::priority_queue ; 253 254T pop_move () { 255T item = std::move (this -> c .front ()); 256 std::pop_heap (this -> c .begin (),this -> c .end (),this -> comp ); 257this -> c .pop_back (); 258return item ; 259 } 260 261void pop ()= delete ; 262}; 263 264struct llm_bigram_bpe { 265struct comparator { 266bool operator()(const llm_bigram_bpe & l ,const llm_bigram_bpe & r )const { 267return l .rank > r .rank || (l .rank == r .rank && l .left > r .left ); 268 } 269 }; 270 271using queue_storage = std::vector < llm_bigram_bpe > ; 272using queue = llama_priority_queue < llm_bigram_bpe ,queue_storage ,comparator > ; 273 llm_symbol::index left ; 274 llm_symbol::index right ; 275 std::string text ; 276int rank ; 277size_t size ; 278}; 279 280struct llm_tokenizer_bpe :llm_tokenizer { 281llm_tokenizer_bpe (const llama_vocab & vocab ) { 282GGML_ASSERT (vocab .get_type ()== LLAMA_VOCAB_TYPE_BPE ); 283switch (vocab .get_pre_type ()) { 284case LLAMA_VOCAB_PRE_TYPE_LLAMA3 : 285regex_exprs = { 286// original regex from tokenizer.json 287//"(?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+", 288 289// adapted: https://github.com/ggml-org/llama.cpp/pull/6920#issuecomment-2080233989 290"(?:'[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+" , 291 }; 292break ; 293case LLAMA_VOCAB_PRE_TYPE_JAIS2 : 294regex_exprs = { 295// original regex from tokenizer.json 296//"(?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{512}(?!\\S)|\\s{256}(?!\\S)|\\s{128}(?!\\S)|\\s{64}(?!\\S)|\\s{32}(?!\\S)|\\s{16}(?!\\S)|\\s{8}(?!\\S)|\\s{4}(?!\\S)|\\s{1,2}(?!\\S)|\\s{1}", 297 298// adapted: same as llama3 but with cascading whitespace pattern 299"(?:'[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{512}(?!\\S)|\\s{256}(?!\\S)|\\s{128}(?!\\S)|\\s{64}(?!\\S)|\\s{32}(?!\\S)|\\s{16}(?!\\S)|\\s{8}(?!\\S)|\\s{4}(?!\\S)|\\s{1,2}(?!\\S)|\\s{1}" , 300 }; 301break ; 302case LLAMA_VOCAB_PRE_TYPE_DBRX : 303case LLAMA_VOCAB_PRE_TYPE_SMAUG : 304regex_exprs = { 305// same as llama3 306"(?:'[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+" , 307 }; 308break ; 309case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM : 310regex_exprs = { 311"[\r\n]" , 312"\\s?[A-Za-zµÀ-ÖØ-öø-ƺƼ-ƿDŽ-ʓʕ-ʯͰ-ͳͶͷͻ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-ՖႠ-ჅᎠ-Ᏽᏸ-ᏽᲐ-ᲺᲽ-Ჿᴀ-ᴫᵫ-ᵷᵹ-ᶚḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℴℹℼ-ℿⅅ-ⅉⅎↃↄⰀ-ⱻⱾ-ⳤⳫ-ⳮⳲⳳꙀ-ꙭꚀ-ꚛꜢ-ꝯꝱ-ꞇꞋ-ꞎꭰ-ꮿff-stﬓ-ﬗA-Za-z𐐀-𐑏𐒰-𐓓𐓘-𐓻𐲀-𐲲𐳀-𐳲𑢠-𑣟𞤀-𞥃]+" , 313"\\s?[!-/:-~!-/:-~‘-‟ -。]+" , 314"\\s+$" , 315"[一-龥ࠀ-一가-]+" , 316"\\p{N}+" , 317 }; 318break ; 319case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK3_LLM : 320case LLAMA_VOCAB_PRE_TYPE_HUNYUAN_DENSE : 321case LLAMA_VOCAB_PRE_TYPE_JOYAI_LLM : 322case LLAMA_VOCAB_PRE_TYPE_HY_V4 : 323regex_exprs = { 324"\\p{N}{1,3}" , 325"[一-龥-ゟ゠-ヿ]+" , 326"[!\"#$%&'()*+,\\-./:;<=>?@\\[\\\\\\]^_`{|}~][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+" , 327 }; 328break ; 329case LLAMA_VOCAB_PRE_TYPE_SPARK2_5 : 330regex_exprs = { 331"\\p{N}{1,3}" , 332"[一-龥-ゟ゠-ヿ]+" , 333"[!\"#$%&'()*+,\\-./:;<=>?@\\[\\\\\\]^_`{|}~][A-Za-z]+|[^\r\n\\p{L}\\p{P}\\p{S}]?[\\p{L}\\p{M}]+| ?[\\p{P}\\p{S}]+|[\r\n]|\\s+(?!\\S)|\\s+" , 334"\\p{N}" , 335 }; 336break ; 337case LLAMA_VOCAB_PRE_TYPE_YOUTU : 338regex_exprs = { 339"[가-힣ㄱ-ㆎ]+|[!…“”‘’—:;,、-〿︰-﹏]+|[ㄅ-ㄯ]+|[一-龥-ゟ゠-ヿ]+" , 340"[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" , 341 }; 342break ; 343case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER : 344regex_exprs = { 345"[\r\n]" , 346"\\s?\\p{L}+" , 347"\\s?\\p{P}+" , 348"[一-龥ࠀ-一가-]+" , 349"\\p{N}" , 350 }; 351break ; 352case LLAMA_VOCAB_PRE_TYPE_FALCON : 353regex_exprs = { 354"[\\p{P}\\$\\+<=>\\^~\\|`]+" , 355"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" , 356"[0-9][0-9][0-9]" , 357 }; 358break ; 359case LLAMA_VOCAB_PRE_TYPE_STARCODER : 360case LLAMA_VOCAB_PRE_TYPE_REFACT : 361case LLAMA_VOCAB_PRE_TYPE_COMMAND_R : 362case LLAMA_VOCAB_PRE_TYPE_SMOLLM : 363case LLAMA_VOCAB_PRE_TYPE_CODESHELL : 364case LLAMA_VOCAB_PRE_TYPE_EXAONE : 365case LLAMA_VOCAB_PRE_TYPE_MINERVA : 366case LLAMA_VOCAB_PRE_TYPE_MELLUM2 : 367regex_exprs = { 368"\\p{N}" , 369"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" , 370 }; 371break ; 372case LLAMA_VOCAB_PRE_TYPE_GPT2 : 373case LLAMA_VOCAB_PRE_TYPE_MPT : 374case LLAMA_VOCAB_PRE_TYPE_OLMO : 375case LLAMA_VOCAB_PRE_TYPE_JAIS : 376case LLAMA_VOCAB_PRE_TYPE_TRILLION : 377case LLAMA_VOCAB_PRE_TYPE_GRANITE_DOCLING : 378regex_exprs = { 379"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" , 380 }; 381break ; 382case LLAMA_VOCAB_PRE_TYPE_STABLELM2 : 383case LLAMA_VOCAB_PRE_TYPE_QWEN2 : 384case LLAMA_VOCAB_PRE_TYPE_HUNYUAN : 385case LLAMA_VOCAB_PRE_TYPE_SOLAR_OPEN : 386regex_exprs = { 387// original regex from tokenizer.json 388// "(?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+" 389"(?:'[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+" , 390 }; 391break ; 392case LLAMA_VOCAB_PRE_TYPE_QWEN35 : 393regex_exprs = { 394// original regex from tokenizer.json 395// "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" 396"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" , 397 }; 398break ; 399case LLAMA_VOCAB_PRE_TYPE_PORO : 400case LLAMA_VOCAB_PRE_TYPE_BLOOM : 401case LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH : 402regex_exprs = { 403" ?[^(\\s|.,!?…。,、।۔،)]+" , 404 }; 405break ; 406case LLAMA_VOCAB_PRE_TYPE_CHATGLM4 : 407regex_exprs = { 408"(?:'[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+" , 409 }; 410break ; 411case LLAMA_VOCAB_PRE_TYPE_VIKING : 412regex_exprs = { 413" ?[^(\\s|.,!?…。,、।۔،)]+" , 414"\\p{N}" , 415 }; 416break ; 417case LLAMA_VOCAB_PRE_TYPE_TEKKEN : 418// original regex from tokenizer.json 419// "[^\\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+" 420regex_exprs = { 421"[^\\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+" , 422 }; 423break ; 424case LLAMA_VOCAB_PRE_TYPE_CHAMELEON : 425// Note: in theory, the special token (sentinel and image token) regex_exprs below 426// are unnecessary, as they are split in `tokenizer_st_partition` anyway. 427// However, since the upstream pre-tokenizer uses them, they are also 428// included here (see https://huggingface.co/facebook/chameleon-7b). 429regex_exprs = { 430"<sentinel:[0-9]+>" ,// Sentinel tokens 431"(IMGIMG)((A|B|C|D|E|F|G|H|I){1,4})Z" ,// Image tokens 432"([\\t\\n]| | )" ,// directly from tokenizer.json 433"\\p{N}" ,// Individual digits 434"[\\p{P}!-/:-@\\[-`{-~]" ,// Punctuation, Isolated 435"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" , 436 }; 437break ; 438case LLAMA_VOCAB_PRE_TYPE_GPT4O : 439case LLAMA_VOCAB_PRE_TYPE_MINIMAX_M2 : 440regex_exprs = { 441// original regex from tokenizer.json 442// "[^\\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+", 443"[^\\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+" , 444 }; 445break ; 446case LLAMA_VOCAB_PRE_TYPE_GRANITE_EMB_MULTI : 447// Same lookaheads as GPT4O but with \p{M} added so combining marks 448// (diacritics) attach to their base letters. Avoids excessive 449// backtracking on scripts that use them heavily (Bengali, Hindi, 450// Telugu, Thai, ...). See PR #22716 for benchmarks. 451regex_exprs = { 452"[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}\\p{M}])([^a-z]))*((?=[\\p{L}\\p{M}])([^A-Z]))+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}\\p{M}])([^a-z]))+((?=[\\p{L}\\p{M}])([^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+" , 453 }; 454break ; 455case LLAMA_VOCAB_PRE_TYPE_TINY_AYA : 456regex_exprs = { 457// original regex from tokenizer.json: "\\d{1,3}(?=(?:\\d{3})*\\b)" 458"\\d{1,3}(?=(?:\\d{3})*\\b)" , 459// original regex from tokenizer.json: "[^\\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+" 460"[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*(?:'[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+" , 461 }; 462break ; 463case LLAMA_VOCAB_PRE_TYPE_KIMI_K2 : 464regex_exprs = { 465// K2 trigger pattern - this will activate the custom K2 handler in unicode.cpp 466// The custom handler implements all K2 patterns with proper Han character exclusion 467"\\p{Han}+" , 468 }; 469break ; 470case LLAMA_VOCAB_PRE_TYPE_SUPERBPE : 471regex_exprs = { 472"\\p{N}+" , 473"(?=(\\d{3})+(?!\\d))" , 474 }; 475break ; 476case LLAMA_VOCAB_PRE_TYPE_BAILINGMOE : 477regex_exprs = { 478// original regex from tokenizer.json 479// "'(?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+" 480// FIXME? Changed possessive quantifiers (?+ and ++) to greedy to avoid errors and imatrix hanging (tried atomic grouping but it's not supported?) 481"'(?:[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+" , 482 }; 483break ; 484case LLAMA_VOCAB_PRE_TYPE_SEED_CODER : 485regex_exprs = { 486// original regex from tokenizer.json 487// "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1}| ?[^\\s\\p{L}\\p{N}\r\n]+|\\s*[\r\n]+|\\s+(?!\\S)|\\s+" 488"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1}| ?[^\\s\\p{L}\\p{N}\\r\\n]+|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" , 489 }; 490break ; 491case LLAMA_VOCAB_PRE_TYPE_UFAKZEKA : 492regex_exprs = { 493// Qwen2 pattern without the English contraction group, so Turkish apostrophe suffixes stay attached 494"[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" , 495 }; 496break ; 497case LLAMA_VOCAB_PRE_TYPE_GROK_2 : 498regex_exprs = { 499// original regex from tokenizer.json 500// "(?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+" 501"(?:'[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+" , 502 }; 503break ; 504case LLAMA_VOCAB_PRE_TYPE_AFMOE : 505regex_exprs = { 506// Digit handling - uses custom implementation in unicode.cpp 507// Groups digits with leading 1-2 based on total length modulo 3 508"\\p{AFMoE_digits}" , 509// CJK and Asian scripts (using direct Unicode literals) 510"[一-鿿㐀-䶿豈--ゟ゠-ヿ・-゚⼀-เ--ក-က-႟ꩠ-ꩿꧠ-가-ᄀ-ᇿ]+" , 511// Main BPE pattern 512"[!\"#$%&'()*+,\\-./:;<=>?@\\[\\\\\\]^_`{|}~][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+" , 513 }; 514break ; 515case LLAMA_VOCAB_PRE_TYPE_LAGUNA : 516regex_exprs = { 517"[^\\n]+|[\\n]+" , 518"(?:'[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+" , 519 }; 520break ; 521case LLAMA_VOCAB_PRE_TYPE_EXAONE_MOE : 522regex_exprs = { 523// original regex from tokenizer.json 524// "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?(?:\\p{L}\\p{M}*(?: \\p{L}\\p{M}*)*)+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]?|\\s*[\\r\\n]|\\s+(?!\\S)|\\s+" 525"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?(?:\\p{L}\\p{M}*(?: \\p{L}\\p{M}*)*)+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]?|\\s*[\\r\\n]|\\s+(?!\\S)|\\s+" , 526 }; 527break ; 528case LLAMA_VOCAB_PRE_TYPE_GEMMA4 : 529// Gemma4 uses SPM-style BPE: spaces are replaced with ▁ by the 530// normalizer, then BPE merges run on the whole text without 531// word-level pre-splitting. We only need to split on newlines 532// since BPE merge lookup asserts no newlines in tokens. 533regex_exprs = { 534"[^\\n]+|[\\n]+" , 535 }; 536byte_encode = false;// uses raw UTF-8, not GPT-2 byte encoding 537break ; 538case LLAMA_VOCAB_PRE_TYPE_SARVAM_MOE : 539// Sarvam uses SPM-style BPE (same shape as Gemma4): spaces replaced with U+2581 540// by the normalizer, BPE merges over the whole text on raw UTF-8. 541regex_exprs = { 542"[^\\n]+|[\\n]+" , 543 }; 544byte_encode = false; 545break ; 546case LLAMA_VOCAB_PRE_TYPE_MINICPM5 : 547regex_exprs = { 548// original regex from tokenizer.json (openbmb/MiniCPM5-1B) 549"\\p{N}{1,3}" , 550// "(?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+" 551"(?:'[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+" , 552 }; 553break ; 554case LLAMA_VOCAB_PRE_TYPE_WHITESPACE : 555// whitespace pre-tokenizer (jinaai/jina-embeddings-v2-base-zh) 556regex_exprs = { 557"\\S+" , 558 }; 559byte_encode = false; 560break ; 561default : 562// default regex for BPE tokenization pre-processing 563regex_exprs = { 564"[\\p{P}\\$\\+<=>\\^~\\|]+" , 565"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" , 566"\\p{N}+" , 567"[0-9][0-9][0-9]" , 568 }; 569break ; 570 } 571 } 572 573 std::vector < std::string > regex_exprs ; 574bool byte_encode = true;// GPT-2 byte encoding; false for SPM-style BPE (raw UTF-8) 575}; 576 577struct llm_tokenizer_bpe_session { 578llm_tokenizer_bpe_session (const llama_vocab & vocab ,const llm_tokenizer_bpe & tokenizer ) :vocab (vocab ),tokenizer (tokenizer ) {} 579 580virtual ~llm_tokenizer_bpe_session ()= default ; 581 582static void append (const llama_token token_id , std::vector < llama_token > & output ) { 583output .push_back (token_id ); 584 } 585 586bool append_bos (std::vector < llama_token > & output )const { 587if (vocab .get_add_bos ()) { 588GGML_ASSERT (vocab .token_bos ()!= LLAMA_TOKEN_NULL ); 589output .push_back (vocab .token_bos ()); 590return true; 591 } 592return false; 593 } 594 595bool append_eos (std::vector < llama_token > & output )const { 596if (vocab .get_add_eos ()) { 597GGML_ASSERT (vocab .token_eos ()!= LLAMA_TOKEN_NULL ); 598output .push_back (vocab .token_eos ()); 599return true; 600 } 601return false; 602 } 603 604void check_double_bos_eos (const std::vector < llama_token > & output )const { 605if (vocab .get_add_bos ()&& output .size () >=2 && output [1 ]== vocab .token_bos ()) { 606LLAMA_LOG_WARN ( 607"%s: Added a BOS token to the prompt as specified by the model but the prompt " 608"also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. " 609"Are you sure this is what you want?\n" ,__FUNCTION__ ); 610 } 611if (vocab .get_add_eos ()&& output .size () >=2 && * (output .end ()- 2 )== vocab .token_eos ()) { 612LLAMA_LOG_WARN ( 613"%s: Added a EOS token to the prompt as specified by the model but the prompt " 614"also ends with a EOS token. So now the final prompt ends with 2 EOS tokens. " 615"Are you sure this is what you want?\n" ,__FUNCTION__ ); 616 } 617 } 618 619virtual void tokenize (const std::string & text , std::vector < llama_token > & output ) { 620int final_prev_index = -1 ; 621const auto word_collection = unicode_regex_split (text ,tokenizer .regex_exprs ,tokenizer .byte_encode ); 622 623symbols_final .clear (); 624auto tok_pre = vocab .get_pre_type (); 625 626for (const auto & word :word_collection ) { 627work_queue = llm_bigram_bpe::queue (); 628symbols .clear (); 629 630int index = 0 ; 631size_t offset = 0 ; 632 633//if (vocab.tokenizer_ignore_merges && vocab.token_to_id.find(word) != vocab.token_to_id.end()) { 634if (vocab .get_ignore_merges ()&& vocab .text_to_token (word )!= LLAMA_TOKEN_NULL ) { 635symbols .emplace_back (llm_symbol {-1 ,-1 ,word .c_str (),word .size ()}); 636offset = word .size (); 637 }else if (tok_pre == LLAMA_VOCAB_PRE_TYPE_GEMMA4 && word .find_first_not_of ('\n' )== std::string::npos ) { 638// fix for gemma 4, ref: https://github.com/ggml-org/llama.cpp/pull/21343 639auto tok = vocab .text_to_token (word ); 640if (tok != LLAMA_TOKEN_NULL ) { 641symbols .emplace_back (llm_symbol {-1 ,-1 ,word .c_str (),word .size ()}); 642offset = word .size (); 643 } 644 } 645 646while (offset < word .size ()) { 647llm_symbol sym ; 648size_t char_len = std::min (word .size ()- offset , (size_t )unicode_len_utf8 (word [offset ])); 649sym .text = word .c_str ()+ offset ; 650sym .n = char_len ; 651offset += sym .n ; 652sym .prev = index - 1 ; 653sym .next = offset == word .size () ?-1 :index + 1 ; 654index ++ ; 655symbols .emplace_back (sym ); 656 } 657for (int i = 1 ;i < (int )symbols .size ();++ i ) { 658add_new_bigram (i - 1 ,i ); 659 } 660 661// build token(s) 662while (!work_queue .empty ()) { 663auto bigram = work_queue .pop_move (); 664 665auto & left_symbol = symbols [bigram .left ]; 666auto & right_symbol = symbols [bigram .right ]; 667 668if (left_symbol .n == 0 || right_symbol .n == 0 ) { 669continue ; 670 } 671 std::string left_token = std::string (left_symbol .text ,left_symbol .n ); 672 std::string right_token = std::string (right_symbol .text ,right_symbol .n ); 673if (left_token + right_token != bigram .text ) { 674continue ;// Skip this bigram if it's outdated 675 } 676 677// merge the right sym into the left one 678left_symbol .n += right_symbol .n ; 679right_symbol .n = 0 ; 680 681// remove the right sym from the chain 682left_symbol .next = right_symbol .next ; 683if (right_symbol .next >=0 ) { 684symbols [right_symbol .next ].prev = bigram .left ; 685 } 686 687add_new_bigram (left_symbol .prev ,bigram .left );// left side of current symbol 688add_new_bigram (bigram .left ,left_symbol .next );// right side of current symbol 689 } 690 691// add the finished tokens to the final list keeping correct order for next and prev 692for (auto & sym :symbols ) { 693if (sym .n > 0 ) { 694sym .prev = final_prev_index ; 695sym .next = -1 ; 696if (final_prev_index != -1 ) { 697symbols_final [final_prev_index ].next = symbols_final .size (); 698 } 699symbols_final .emplace_back (sym ); 700final_prev_index = symbols_final .size ()- 1 ; 701 } 702 } 703 } 704 705symbols = symbols_final ; 706 707if (!symbols .empty ()) { 708for (int i = 0 ;i != -1 ;i = symbols [i ].next ) { 709auto & symbol = symbols [i ]; 710if (symbol .n == 0 ) { 711continue ; 712 } 713 714const std::string str = std::string (symbol .text ,symbol .n ); 715const auto token = vocab .text_to_token (str ); 716 717if (token == LLAMA_TOKEN_NULL ) { 718for (auto j = str .begin ();j != str .end ();++ j ) { 719llama_token token_multibyte = LLAMA_TOKEN_NULL ; 720if (tokenizer .byte_encode ) { 721 std::string byte_str (1 ,* j ); 722token_multibyte = vocab .text_to_token (byte_str ); 723 }else { 724// For non-byte-encoded BPE (e.g. gemma-4), byte tokens use <0xXX> format 725static const char * hex = "0123456789ABCDEF" ; 726const uint8_t ch = (uint8_t )* j ; 727const char buf [7 ]= {'<' ,'0' ,'x' ,hex [ch >>4 ],hex [ch & 15 ],'>' ,0 }; 728token_multibyte = vocab .text_to_token (buf ); 729 } 730if (token_multibyte != LLAMA_TOKEN_NULL ) { 731output .push_back (token_multibyte ); 732 } 733 } 734 }else { 735output .push_back (token ); 736 } 737 } 738 } 739 } 740 741private : 742void add_new_bigram (int left ,int right ) { 743if (left == -1 || right == -1 ) { 744return ; 745 } 746 std::string left_token = std::string (symbols [left ].text ,symbols [left ].n ); 747 std::string right_token = std::string (symbols [right ].text ,symbols [right ].n ); 748 749int rank_found = -1 ; 750 751rank_found = vocab .find_bpe_rank (left_token ,right_token ); 752 753if (rank_found < 0 ) { 754return ; 755 } 756 757llm_bigram_bpe bigram ; 758 759bigram .left = left ; 760bigram .right = right ; 761bigram .text = left_token + right_token ; 762bigram .size = left_token .size ()+ right_token .size (); 763bigram .rank = rank_found ; 764 765work_queue .push (bigram ); 766 } 767 768const llama_vocab & vocab ; 769const llm_tokenizer_bpe & tokenizer ; 770 771 std::vector < llm_symbol > symbols ; 772 std::vector < llm_symbol > symbols_final ; 773 llm_bigram_bpe::queue work_queue ; 774}; 775 776// 777// WPM tokenizer 778// 779 780struct llm_tokenizer_wpm :llm_tokenizer { 781llm_tokenizer_wpm (const llama_vocab & /*vocab*/ ) {} 782}; 783 784struct llm_tokenizer_wpm_session { 785llm_tokenizer_wpm_session (const llama_vocab & vocab ) :vocab (vocab ) {} 786 787void tokenize (const std::string & text , std::vector < llama_token > & output ) { 788// normalize and split by whitespace 789 std::vector < std::string > words = preprocess (text ,vocab .get_normalizer_opts ()); 790// bos token prepended already 791 792// find the longest tokens that form the words 793for (const std::string & word :words ) { 794// skip empty words 795if (word .size ()== 0 ) { 796continue ; 797 } 798 799// prepend phantom space 800const std::string word1 = "\xe2\x96\x81" + word ; 801const int n = word1 .size (); 802 803const size_t current_tokens = output .size (); 804 805// we're at the start of a new word 806// move through character position in word 807for (int i = 0 ;i < n ;++ i ) { 808// loop through possible match length 809bool match = false; 810for (int j = std::min (n ,i + vocab .max_token_len ()+ 1 );j > i ;j -- ) { 811auto id = vocab .text_to_token (word1 .substr (i ,j - i )); 812if (id != LLAMA_TOKEN_NULL ) { 813output .push_back (id ); 814match = true; 815i = j - 1 ; 816break ; 817 } 818 } 819 820if (!match ) {// discard all 821output .resize (current_tokens ); 822break ;// and discard next tokens 823 } 824 } 825 826// we didn't find any matches for this word 827if (current_tokens == output .size ()) { 828output .push_back (vocab .token_unk ()); 829 } 830 } 831 } 832 833// TODO: reduce string copies by using cpts_offs array 834static std::vector < std::string > preprocess (const std::string & text ,const llama_vocab::normalizer_options & normalizer_opts ) { 835 std::vector < uint32_t > cpts = unicode_cpts_from_utf8 (text ); 836if (normalizer_opts .strip_accents ) { 837cpts = unicode_cpts_normalize_nfd (cpts ); 838 } 839 std::vector < std::string > words (1 ,"" ); 840 841for (const uint32_t cpt :cpts ) { 842const auto flags = unicode_cpt_flags_from_cpt (cpt ); 843 844if (flags .is_whitespace ) { 845if (words .back ().size ()) {// finish previous word if any 846words .emplace_back (); 847 } 848continue ; 849 } 850 851assert (!flags .is_separator ); 852if (cpt == 0 || cpt == 0xFFFD || flags .is_control ) { 853continue ; 854 } 855 856if (normalizer_opts .strip_accents && flags .is_accent_mark ) { 857continue ; 858 } 859 860const std::string s = unicode_cpt_to_utf8 (normalizer_opts .lowercase ?unicode_tolower (cpt ) :cpt ); 861if (flags .is_punctuation || (cpt < 0x7F && flags .is_symbol )|| is_chinese_char (cpt )) { 862if (words .back ().size ()) {// finish previous word if any 863words .emplace_back (); 864 } 865words .back ()= s ;// single char word 866words .emplace_back ();// start a new word 867 }else { 868words .back ()+= s ;// append char to word 869 } 870 } 871 872if (!words .back ().size ()) { 873words .pop_back (); 874 } 875 876return words ; 877 } 878 879static bool is_chinese_char (uint32_t cpt ) { 880return 881 (cpt >=0x04E00 && cpt <=0x09FFF )|| 882 (cpt >=0x03400 && cpt <=0x04DBF )|| 883 (cpt >=0x20000 && cpt <=0x2A6DF )|| 884 (cpt >=0x2A700 && cpt <=0x2B73F )|| 885 (cpt >=0x2B740 && cpt <=0x2B81F )|| 886 (cpt >=0x2B920 && cpt <=0x2CEAF )|| // this should be 0x2B820 but in hf rust code it is 0x2B920 887 (cpt >=0x0F900 && cpt <=0x0FAFF )|| 888 (cpt >=0x2F800 && cpt <=0x2FA1F ); 889//(cpt >= 0x3000 && cpt <= 0x303F) || 890//(cpt >= 0xFF00 && cpt <= 0xFFEF); 891 } 892 893private : 894const llama_vocab & vocab ; 895// currently unused 896// const llm_tokenizer_wpm * wpm_tokenizer; 897}; 898 899// 900// UGM tokenizer 901// 902 903struct llm_tokenizer_ugm :llm_tokenizer { 904llm_tokenizer_ugm (const llama_vocab & vocab ,const std::vector < char > & precompiled_charsmap ) { 905if (precompiled_charsmap .size ()> 0 ) { 906size_t charsmap_offset = 0 ; 907 908// First four bytes of precompiled_charsmap contains length of binary 909// blob containing XOR-compressed compact double array (XCDA) entries 910uint32_t xcda_blob_size = * (const uint32_t * )& precompiled_charsmap [0 ]; 911charsmap_offset += sizeof (xcda_blob_size ); 912 913// Next xcda_blob_size bytes contain entries of XOR-compressed compact 914// double array (XCDA). Each entry is bit-packed into a 32-bit integer. 915xcda_array = (const uint32_t * )& precompiled_charsmap [charsmap_offset ]; 916xcda_array_size = xcda_blob_size /sizeof (uint32_t ); 917charsmap_offset += xcda_blob_size ; 918 919// Remaining bytes of precompiled charsmap contain null-terminated 920// replacement strings for prefixes matched by the XCDA. 921prefix_replacements = & precompiled_charsmap [charsmap_offset ]; 922prefix_replacements_size = precompiled_charsmap .size ()- charsmap_offset ; 923 } 924 925for (uint32_t id = 0 ;id < vocab .n_tokens ();++ id ) { 926const auto & token_data = vocab .get_token_data (id ); 927 928if (vocab .is_normal (id )) { 929min_score = std::min < float > (min_score ,token_data .score ); 930max_score = std::max < float > (max_score ,token_data .score ); 931 } 932 933if (vocab .is_normal (id )|| 934vocab .is_user_defined (id )|| 935vocab .is_unused (id )) { 936token_matcher .insert (token_data .text .data (),token_data .text .size (),id ); 937 } 938 939if (vocab .is_user_defined (id )) { 940user_defined_token_matcher .insert (token_data .text .data (),token_data .text .size ()); 941 } 942 } 943 944unknown_token_score = min_score - unknown_token_score_penalty ; 945 } 946 947// escaped space symbol - U+2581 (Lower One Eighth Block) 948const std::string escaped_space = "\xE2\x96\x81" ; 949 950const char * prefix_replacements = NULL ; 951size_t prefix_replacements_size = 0 ; 952 953const uint32_t * xcda_array = NULL ; 954size_t xcda_array_size = 0 ; 955 956struct naive_trie user_defined_token_matcher ; 957 958float min_score = FLT_MAX ; 959float max_score = - FLT_MAX ; 960 961float unknown_token_score_penalty = 10.0 ; 962float unknown_token_score ; 963 964struct naive_trie token_matcher ; 965}; 966 967struct llm_tokenizer_ugm_session { 968llm_tokenizer_ugm_session (const llama_vocab & vocab ,const llm_tokenizer_ugm & tokenizer ) :vocab (vocab ),tokenizer (tokenizer ) {} 969 970/* This implementation is based on SentencePiece optimized Viterbi algorithm for 971* unigram language models. The general idea is to: 972* - move along the input sequence in steps of one UTF code point, 973* - at each step find all possible tokenizations of the prefix by 974* traversing the tokens trie, 975* - for each tokenization store the best one so far (by higher score) 976* - use the position in sequence after given token as an index to store 977* results 978* - if there was no valid tokenization of the current UTF code point 979* then use unknown token with additional score penalty 980* After processing the whole sequence we backtrack from the end to get 981* the best tokenization. 982*/ 983void tokenize (const std::string & text , std::vector < llama_token > & output ) { 984// get current size of output (for reversal later) 985size_t output_size = output .size (); 986 987// normalize the input first 988 std::string normalized ; 989normalize (text ,& normalized ); 990size_t input_len = normalized .size (); 991if (input_len == 0 ) { 992return ; 993 } 994 995// initialize score_sum to -FLT_MAX so it will be always lower than sums of token scores 996 std::vector < struct best_tokenization > tokenization_results (input_len + 1 , {vocab .token_unk (),0 ,- DBL_MAX }); 997// at the beginning tokenization score is zero 998tokenization_results [0 ]= {vocab .token_unk (),0 ,0 }; 999 1000for (size_t input_offset = 0 ;input_offset < input_len ;) { 1001size_t prefix_offset = input_offset ; 1002// calculate how many code units are in the currently processed UTF code point 1003size_t n_utf8_code_units = std::min < size_t > (unicode_len_utf8 (normalized [input_offset ]),input_len - input_offset ); 1004 1005// traverse the token matcher trie to find a matching token 1006bool single_codepoint_token_found = false; 1007const struct best_tokenization & current_best = tokenization_results [input_offset ]; 1008const struct naive_trie * node = tokenizer .token_matcher .traverse (normalized [prefix_offset ++ ]); 1009 1010while (prefix_offset <=input_len && node != NULL ) { 1011// check if we found valid token in prefix 1012if (node -> has_value ) { 1013// check if it corresponds to the whole UTF code point 1014if (prefix_offset - input_offset == n_utf8_code_units ) { 1015single_codepoint_token_found = true; 1016 } 1017llama_token token_id = node -> value ; 1018const auto & token_data = vocab .get_token_data (token_id ); 1019 1020// we set the user-defined token scores to 0 to make them more likely to be selected 1021// (normal token scores are log probabilities, so they are negative) 1022// score type is double here to make tokenization results exactly 1023// the same as in the HF tokenizer using SentencePiece 1024const double token_score = vocab .is_user_defined (token_id ) ?0.0 :token_data .score ; 1025const double challenger_score = current_best .score_sum + token_score ; 1026struct best_tokenization & current_champ = tokenization_results [prefix_offset ]; 1027if (challenger_score > current_champ .score_sum ) { 1028struct best_tokenization challenger = {token_id ,input_offset ,challenger_score }; 1029current_champ = challenger ; 1030 } 1031 } 1032node = node -> traverse (normalized [prefix_offset ++ ]); 1033 } 1034 1035// if we didn't find a valid token corresponding to the whole UTF code point 1036// then use unknown token as the tokenization of this UTF code point 1037if (!single_codepoint_token_found ) { 1038const double challenger_score = current_best .score_sum + tokenizer .unknown_token_score ; 1039prefix_offset = input_offset + n_utf8_code_units ; 1040struct best_tokenization & current_champ = tokenization_results [prefix_offset ]; 1041if (challenger_score > current_champ .score_sum ) { 1042struct best_tokenization challenger = {vocab .token_unk (),input_offset ,challenger_score }; 1043current_champ = challenger ; 1044 } 1045 } 1046 1047// move to the next UTF code point 1048input_offset += n_utf8_code_units ; 1049 } 1050 1051// now backtrack from the end to gather token ids of the best tokenization 1052// merge sequences of consecutive unknown tokens into single unknown tokens 1053bool is_prev_unknown = false; 1054for (struct best_tokenization & tokenization = tokenization_results [input_len ]; ;tokenization = tokenization_results [tokenization .input_offset ]) { 1055bool is_unknown = tokenization .token_id == vocab .token_unk (); 1056if (!(is_prev_unknown && is_unknown )) { 1057output .push_back (tokenization .token_id ); 1058 } 1059if (tokenization .input_offset == 0 ) { 1060break ; 1061 } 1062is_prev_unknown = is_unknown ; 1063 } 1064 1065// reverse the output since we added tokens starting from the end of the input 1066 std::reverse (output .begin ()+ output_size ,output .end ()); 1067 } 1068 1069private : 1070 1071// helper structure for returning normalization results 1072struct normalization_result { 1073const char * normalized ; 1074size_t normalized_len ; 1075size_t consumed_input ; 1076 }; 1077 1078void normalize (const std::string & input , std::string * normalized ) { 1079normalized -> clear (); 1080normalized -> reserve (input .size ()* 3 ); 1081 1082const std::string space = vocab .get_escape_whitespaces () ?tokenizer .escaped_space :" " ; 1083 1084const bool shall_prepend_space = !vocab .get_treat_whitespace_as_suffix ()&& vocab .get_add_space_prefix (); 1085const bool shall_append_space = vocab .get_treat_whitespace_as_suffix ()&& vocab .get_add_space_prefix (); 1086const bool shall_merge_spaces = vocab .get_remove_extra_whitespaces (); 1087 1088bool is_space_prepended = false; 1089bool processing_non_ws = false; 1090 1091size_t input_len = input .size (); 1092 1093for (size_t input_offset = 0 ;input_offset < input_len ; ) { 1094auto norm_res = normalize_prefix (input ,input_offset ); 1095for (size_t i = 0 ;i < norm_res .normalized_len ;i ++ ) { 1096char c = norm_res .normalized [i ]; 1097if (c != ' ' ) { 1098if (!processing_non_ws ) { 1099processing_non_ws = true; 1100if ((shall_prepend_space && !is_space_prepended )|| shall_merge_spaces ) { 1101normalized -> append (space ); 1102is_space_prepended = true; 1103 } 1104 } 1105normalized -> push_back (c ); 1106 }else { 1107if (processing_non_ws ) { 1108processing_non_ws = false; 1109 } 1110if (!shall_merge_spaces ) { 1111normalized -> append (space ); 1112 } 1113 } 1114 } 1115 1116input_offset += norm_res .consumed_input ; 1117 } 1118 1119if (shall_append_space ) { 1120normalized -> append (space ); 1121 } 1122 } 1123 1124/* 1125* This structure is a view wrapper for XOR-compressed double array (XCDA) 1126* See Shunsuke Kanda (2018). Space- and Time-Efficient String Dictionaries. 1127* Each bit-packed entry contains: 1128* - BASE array value in bits 10-30 1129* - LCHECK array value in bits 0-7 1130* - LEAF array value in bit 9 1131* Entries containing indexes of replacement sequences have set bit 31 1132*/ 1133struct xcda_array_view { 1134public : 1135xcda_array_view (const uint32_t * xcda_array ,size_t xcda_array_size ) :xcda_array (xcda_array ),xcda_array_size (xcda_array_size ) { 1136 } 1137uint32_t get_base (size_t index ) { 1138uint32_t packed_node = get_node (index ); 1139return (packed_node >>10 ) << ((packed_node & (1U <<9 )) >>6 ); 1140 } 1141uint32_t get_lcheck (size_t index ) { 1142uint32_t packed_node = get_node (index ); 1143return packed_node & ((1U <<31 ) |0xff ); 1144 } 1145bool get_leaf (size_t index ) { 1146uint32_t packed_node = get_node (index ); 1147return (packed_node >>8 )& 1 ; 1148 } 1149uint32_t get_value (size_t index ) { 1150uint32_t packed_node = get_node (index ); 1151return packed_node & ((1U <<31 )- 1 ); 1152 } 1153private : 1154uint32_t get_node (size_t index ) { 1155if (index >=xcda_array_size ) { 1156throw std::runtime_error ("Index out of array bounds in XCDA array!" ); 1157 } 1158return xcda_array [index ]; 1159 } 1160const uint32_t * xcda_array ; 1161size_t xcda_array_size ; 1162 }; 1163 1164// this structure stores the best tokenization so far at input_offset 1165struct best_tokenization { 1166llama_token token_id ; 1167size_t input_offset ; 1168double score_sum ; 1169 }; 1170 1171struct normalization_result normalize_prefix (const std::string & input ,size_t input_offset ) { 1172if (input_offset == input .size ()) { 1173return {& input [input_offset ],0 ,0 }; 1174 } 1175 1176// if input prefix matches some user-defined token return this token as normalization result 1177auto user_defined_token_match = 1178tokenizer .user_defined_token_matcher .get_longest_prefix (& input [input_offset ],input .size ()- input_offset ); 1179if (user_defined_token_match .second > 0 ) { 1180return {& input [input_offset ],user_defined_token_match .second ,user_defined_token_match .second }; 1181 } 1182 1183size_t longest_prefix_length = 0 ; 1184size_t longest_prefix_offset = 0 ; 1185 1186if (tokenizer .xcda_array_size > 0 ) { 1187struct xcda_array_view xcda_view (tokenizer .xcda_array ,tokenizer .xcda_array_size ); 1188 1189// Find the longest normalized sequence matching the input prefix by walking 1190// the XOR-compressed compact double array (XCDA) starting from the root node 1191// We find the index of the next node by calculating BASE[s] ^ c where s is 1192// the index of the previous node and c is a numerical character value 1193uint32_t node_index = 0 ; 1194// get BASE of the root node 1195node_index = xcda_view .get_base (node_index ); 1196for (size_t prefix_offset = input_offset ;prefix_offset < input .size ();prefix_offset ++ ) { 1197unsigned char c = input [prefix_offset ]; 1198if (c == 0 ) { 1199break ; 1200 } 1201node_index ^=c ; 1202// if value of LCHECK is not c it means that this is not a child of 1203// the previous node, so we stop matching 1204if (xcda_view .get_lcheck (node_index )!= c ) { 1205break ; 1206 } 1207bool is_leaf = xcda_view .get_leaf (node_index ); 1208// get BASE of the current node 1209node_index ^=xcda_view .get_base (node_index ); 1210// if LEAF of the current node is true, it means that its BASE points to the node 1211// containing index of replacement sequence for currently matched input prefix 1212if (is_leaf ) 1213 { 1214longest_prefix_length = prefix_offset - input_offset + 1 ; 1215// get index of replacement sequence for currently matched input prefix 1216longest_prefix_offset = xcda_view .get_value (node_index ); 1217 } 1218 } 1219 } 1220 1221if (longest_prefix_length > 0 ) { 1222// we have a match, so return the replacement sequence 1223if (longest_prefix_offset >=tokenizer .prefix_replacements_size ) { 1224throw std::runtime_error ("Index out of array bounds in precompiled charsmap!" ); 1225 } 1226const char * prefix_replacement = & (tokenizer .prefix_replacements )[longest_prefix_offset ]; 1227size_t max_len = tokenizer .prefix_replacements_size - longest_prefix_offset ; 1228size_t repl_len = 0 ; 1229while (repl_len < max_len && prefix_replacement [repl_len ]!= '\0' ) { 1230repl_len ++ ; 1231 } 1232if (repl_len == max_len ) { 1233throw std::runtime_error ("Unterminated string in precompiled charsmap!" ); 1234 } 1235return {prefix_replacement ,repl_len ,longest_prefix_length }; 1236 } 1237 1238// check if the input prefix contains a valid sequence of UTF-8 code units 1239try { 1240// if yes, return this sequence unmodified 1241size_t prefix_offset = input_offset ; 1242unicode_cpt_from_utf8 (input ,prefix_offset ); 1243return {& input [input_offset ],prefix_offset - input_offset ,prefix_offset - input_offset }; 1244 }catch (std::invalid_argument & /*ex*/ ) { 1245// if no, consume 1 byte and return U+FFFD - REPLACEMENT CHARACTER 1246return {"\xEF\xBF\xBD" ,3 ,1 }; 1247 } 1248 } 1249 1250const llama_vocab & vocab ; 1251const llm_tokenizer_ugm & tokenizer ; 1252}; 1253 1254// 1255// RWKV tokenizer 1256// 1257 1258static std::vector < uint8_t > llama_unescape_rwkv_token (const std::string & escaped ) { 1259 std::vector < uint8_t > output ; 1260output .reserve (escaped .size ()); 1261 1262// Parser state 1263bool escaping = false; 1264uint8_t hex_remaining = 0 ; 1265uint8_t hex_acc = 0 ; 1266 1267// Step through characters, performing parsing 1268for (const char & c :escaped ) { 1269// If we're parsing a hex code, interpret the next character 1270if (hex_remaining != 0 ) { 1271uint8_t value = (c >='a' ) ? (c - 'a' + 10 ) : (c - '0' ); 1272hex_acc = (hex_acc <<4 )+ value ; 1273 1274hex_remaining -= 1 ; 1275if (hex_remaining == 0 ) { 1276output .push_back (hex_acc ); 1277hex_acc = 0 ; 1278 } 1279 1280continue ; 1281 } 1282 1283// If we got an escape character, interpret it 1284if (escaping ) { 1285if (c == 't' ) { 1286output .push_back ('\t' ); 1287 }else if (c == 'n' ) { 1288output .push_back ('\n' ); 1289 }else if (c == 'r' ) { 1290output .push_back ('\r' ); 1291 }else if (c == 'x' ) { 1292hex_remaining = 2 ; 1293 }else { 1294output .push_back (c ); 1295 } 1296 1297escaping = false; 1298continue ; 1299 } 1300 1301if (c == '\\' ) { 1302escaping = true; 1303continue ; 1304 } 1305 1306output .push_back (c ); 1307 } 1308 1309return output ; 1310} 1311 1312struct llm_tokenizer_rwkv :llm_tokenizer { 1313llm_tokenizer_rwkv (const llama_vocab & vocab ) { 1314// RWKV supports arbitrary byte tokens, but the vocab struct only supports string tokens. 1315// For now, we decode the vocab here into the lookup we'll use for tokenization. 1316 1317// build trie 1318for (uint32_t id = 0 ;id < vocab .n_tokens ();++ id ) { 1319const auto & data = vocab .get_token_data (id ); 1320const auto text = llama_unescape_rwkv_token (data .text ); 1321token_matcher .insert ((const char * )text .data (),text .size (),id ); 1322 } 1323 } 1324 1325struct naive_trie token_matcher ; 1326}; 1327 1328struct llm_tokenizer_rwkv_session { 1329llm_tokenizer_rwkv_session (const llama_vocab & vocab ,const llm_tokenizer_rwkv & tokenizer ) :vocab (vocab ),tokenizer (tokenizer ) {} 1330 1331void tokenize (const std::string & text , std::vector < llama_token > & output ) { 1332uint32_t position = 0 ; 1333while (position < text .size ()) { 1334const struct naive_trie * node = tokenizer .token_matcher .traverse (text [position ]); 1335if (node == NULL ) { 1336// no matching token found, add unknown token 1337output .push_back (vocab .token_unk ()); 1338position += 1 ; 1339continue ; 1340 } 1341 1342// traverse the trie to find the longest matching token 1343uint32_t token_id = 0 ; 1344uint32_t token_length = 0 ; 1345while (node != NULL ) { 1346if (node -> has_value ) { 1347token_id = node -> value ; 1348token_length = position + 1 ; 1349 } 1350if (position + 1 >=text .size ()) { 1351break ; 1352 } 1353node = node -> traverse (text [++ position ]); 1354 } 1355 1356// add the longest matching token 1357output .push_back (token_id ); 1358position = token_length ; 1359 } 1360 } 1361 1362private : 1363const llama_vocab & vocab ; 1364const llm_tokenizer_rwkv & tokenizer ; 1365}; 1366 1367struct llm_tokenizer_plamo2 :llm_tokenizer { 1368llm_tokenizer_plamo2 (const llama_vocab & vocab ) { 1369build (vocab ); 1370 } 1371 1372void build (const llama_vocab & vocab ) { 1373// Reset internal structures 1374tokens_ .clear (); 1375bytes_ .assign (256 ,0 ); 1376to_suffix_id_ .clear (); 1377table_ .clear (); 1378 1379// Build token list and byte mapping 1380 std::unordered_map < std::string ,float > suffix_to_score ; 1381 std::unordered_map < std::string ,llama_token > token_to_id ; 1382 1383for (size_t token_id = 0 ;token_id < vocab .n_tokens ();++ token_id ) { 1384const auto & entry = vocab .get_token_data (token_id ); 1385tokens_ .push_back (entry .text ); 1386token_to_id [entry .text ]= static_cast < llama_token > (token_id ); 1387 1388// Handle byte tokens 1389if (vocab .is_byte (token_id )) { 1390if (entry .text .length ()== 6 && entry .text .substr (0 ,3 )== "<0x" && entry .text .back ()== '>' ) { 1391 std::string hex_str = entry .text .substr (3 ,2 ); 1392if (std::isxdigit (static_cast < unsigned char > (hex_str [0 ]))&& std::isxdigit (static_cast < unsigned char > (hex_str [1 ]))) { 1393int byte_val = std::stoi (hex_str ,nullptr ,16 ); 1394bytes_ [byte_val ]= static_cast < llama_token > (token_id ); 1395 } 1396 } 1397continue ; 1398 } 1399 1400// Add token and all its suffixes to suffix_to_score 1401suffix_to_score [entry .text ]= entry .score ; 1402 1403// Extract suffixes character by character (UTF-8 aware) 1404 std::vector < uint32_t > cpts = unicode_cpts_from_utf8 (entry .text ); 1405for (size_t i = 1 ;i < cpts .size ();++ i ) { 1406 std::string suffix ; 1407for (size_t j = i ;j < cpts .size ();++ j ) { 1408suffix += unicode_cpt_to_utf8 (cpts [j ]); 1409 } 1410if (suffix_to_score .find (suffix )== suffix_to_score .end ()) { 1411suffix_to_score [suffix ]= std::numeric_limits < float > ::quiet_NaN (); 1412 } 1413 } 1414 } 1415 1416// Check that all byte tokens are set 1417for (int i = 0 ;i < 256 ;++ i ) { 1418if (bytes_ [i ]== 0 ) { 1419throw std::runtime_error ("Byte token for <0x" + std::to_string (i )+ "> is not set" ); 1420 } 1421 } 1422 1423// Build suffix list in lexicographical order of reversed strings 1424 std::vector < std::string > suffixes ; 1425suffixes .reserve (suffix_to_score .size ()+ 1 ); 1426for (const auto & pair :suffix_to_score ) { 1427suffixes .push_back (pair .first ); 1428 } 1429suffixes .push_back ("" );// Empty suffix 1430 1431 std::sort (suffixes .begin (),suffixes .end (), [](const std::string & a ,const std::string & b ) { 1432 std::string rev_a (a .rbegin (),a .rend ()); 1433 std::string rev_b (b .rbegin (),b .rend ()); 1434return rev_a < rev_b ; 1435 }); 1436 1437// Build suffix_to_id and to_suffix_id_ 1438 std::unordered_map < std::string ,int32_t > suffix_to_id ; 1439int32_t num_pieces = 0 ; 1440 1441for (const auto & suffix :suffixes ) { 1442suffix_to_id [suffix ]= num_pieces ; 1443if (!suffix .empty ()) { 1444 std::vector < uint32_t > cpts = unicode_cpts_from_utf8 (suffix ); 1445 1446 std::string remaining ; 1447for (size_t i = 1 ;i < cpts .size ();++ i ) { 1448remaining += unicode_cpt_to_utf8 (cpts [i ]); 1449 } 1450 1451int64_t piece_code = (static_cast < int64_t > (cpts [0 ]) <<32 ) |suffix_to_id [remaining ]; 1452to_suffix_id_ [piece_code ]= num_pieces ; 1453 1454// Count number of pieces for this suffix 1455int32_t pieces_for_suffix = 1 ;// sentinel row 1456for (int32_t piece_length = static_cast < int32_t > (cpts .size ());piece_length > 0 ;-- piece_length ) { 1457 std::string piece ; 1458for (int32_t i = 0 ;i < piece_length ;++ i ) { 1459piece += unicode_cpt_to_utf8 (cpts [i ]); 1460 } 1461if (suffix_to_score .find (piece )!= suffix_to_score .end ()) { 1462pieces_for_suffix ++ ; 1463 } 1464 } 1465num_pieces += pieces_for_suffix ; 1466 }else { 1467num_pieces ++ ;// Empty suffix contributes one piece (sentinel row) 1468 } 1469 } 1470 1471// Build flattened table 1472table_ .resize (num_pieces , std::vector < int32_t > (4 ,0 )); 1473int32_t table_idx = 0 ; 1474 1475for (const auto & suffix :suffixes ) { 1476// Add all prefixes of the suffix to the table (in decreasing order of length) 1477 std::vector < uint32_t > cpts = unicode_cpts_from_utf8 (suffix ); 1478for (int32_t piece_length = static_cast < int32_t > (cpts .size ());piece_length > 0 ;-- piece_length ) { 1479 std::string piece ; 1480for (int32_t i = 0 ;i < piece_length ;++ i ) { 1481piece += unicode_cpt_to_utf8 (cpts [i ]); 1482 } 1483 1484auto score_it = suffix_to_score .find (piece ); 1485if (score_it == suffix_to_score .end ()) { 1486continue ; 1487 } 1488 1489table_ [table_idx ][TABLE_PIECE_LENGTH ]= piece_length ; 1490auto token_it = token_to_id .find (piece ); 1491table_ [table_idx ][TABLE_TOKEN_ID ]= (token_it != token_to_id .end ()) ?token_it -> second :-1 ; 1492 1493float score = score_it -> second ; 1494table_ [table_idx ][TABLE_SCORE ]= std::isfinite (score ) ? 1495static_cast < int32_t > (std::round (score * 1e4 )) :INVALID_SCORE ; 1496table_ [table_idx ][TABLE_PIECE_ID ]= suffix_to_id [piece ]; 1497 1498table_idx ++ ; 1499 } 1500 1501// Add sentinel row 1502table_ [table_idx ][TABLE_PIECE_LENGTH ]= 1 ; 1503table_ [table_idx ][TABLE_TOKEN_ID ]= -1 ; 1504table_ [table_idx ][TABLE_SCORE ]= UNKNOWN_SCORE ; 1505table_idx ++ ; 1506 } 1507 } 1508 1509 std::vector < llama_token > encode (const std::string & text )const { 1510 std::vector < uint32_t > unicode_data = unicode_cpts_from_utf8 (text ); 1511// Skip the first code point if it is a BOM (Byte Order Mark) 1512if (!unicode_data .empty ()&& unicode_data [0 ]== 0xFEFF ) { 1513unicode_data .erase (unicode_data .begin ()); 1514 } 1515 1516if (unicode_data .empty ()) { 1517return {}; 1518 } 1519 1520const size_t data_len = unicode_data .size (); 1521 1522// Initialize scores array (dynamic programming) 1523 std::vector < int64_t > scores (data_len + 1 ,static_cast < int64_t > (1 ) <<60 ); 1524scores [data_len ]= 0 ; 1525 1526// Path array to track best tokenization 1527 std::vector < std::vector < int32_t >> path (data_len + 1 , std::vector < int32_t > (3 ,0 )); 1528 1529int32_t suffix_id = 0 ; 1530 1531// Process from end to beginning 1532for (int i = static_cast < int > (data_len )- 1 ;i >=0 ;-- i ) { 1533uint32_t c = unicode_data [i ]; 1534 1535// Find next suffix ID 1536for (size_t p = suffix_id ;p < table_ .size ();++ p ) { 1537int64_t piece_code = (static_cast < int64_t > (c ) <<32 ) |table_ [p ][TABLE_PIECE_ID ]; 1538auto it = to_suffix_id_ .find (piece_code ); 1539suffix_id = (it != to_suffix_id_ .end ()) ?it -> second :0 ; 1540 1541if (suffix_id > 0 || table_ [p ][TABLE_SCORE ]== UNKNOWN_SCORE ) { 1542break ; 1543 } 1544 } 1545 1546// Update best path 1547for (size_t p = suffix_id ;p < table_ .size ();++ p ) { 1548int32_t score = table_ [p ][TABLE_SCORE ]; 1549if (score > INVALID_SCORE ) { 1550int32_t piece_length = table_ [p ][TABLE_PIECE_LENGTH ]; 1551int64_t s = scores [i + piece_length ]- score ; 1552 1553if (s < scores [i ]) { 1554scores [i ]= s ; 1555path [i ][PATH_TOKEN_LENGTH ]= piece_length ; 1556path [i ][PATH_TOKEN_ID ]= table_ [p ][TABLE_TOKEN_ID ]; 1557path [i ][PATH_NUM_TOKENS ]= path [i + piece_length ][PATH_NUM_TOKENS ]+ 1 ; 1558 1559if (score == UNKNOWN_SCORE ) { 1560// Add UTF-8 byte count 1561path [i ][PATH_NUM_TOKENS ]+= (c >=0x80 )+ (c >=0x800 )+ (c >=0x10000 ); 1562 } 1563 } 1564 } 1565 1566if (score == UNKNOWN_SCORE ) { 1567break ; 1568 } 1569 } 1570 } 1571 1572// Decode the best path 1573 std::vector < llama_token > token_ids ; 1574token_ids .reserve (path [0 ][PATH_NUM_TOKENS ]); 1575 1576int pos = 0 ; 1577while (pos < static_cast < int > (data_len )) { 1578if (path [pos ][PATH_TOKEN_ID ] >=0 ) { 1579token_ids .push_back (path [pos ][PATH_TOKEN_ID ]); 1580 }else { 1581// Fall back to byte tokens 1582uint32_t c = unicode_data [pos ]; 1583int s = 1 + (c >=0x80 )+ (c >=0x800 )+ (c >=0x10000 ); 1584 1585for (int i = 0 ;i < s ;++ i ) { 1586uint8_t b ; 1587if (s == 1 ) { 1588b = c ; 1589 }else { 1590if (i == 0 ) { 1591b = (0xF00 >>s )& 0xFF ; 1592 }else { 1593b = 0x80 ; 1594 } 1595 } 1596token_ids .push_back (bytes_ [b | ((c >> ((s - i - 1 )* 6 ))& 0x3F )]); 1597 } 1598 } 1599 1600assert (path [pos ][PATH_TOKEN_LENGTH ]> 0 ); 1601pos += path [pos ][PATH_TOKEN_LENGTH ]; 1602 } 1603 1604return token_ids ; 1605 } 1606private : 1607// Constants for table structure 1608static constexpr int32_t TABLE_PIECE_LENGTH = 0 ; 1609static constexpr int32_t TABLE_TOKEN_ID = 1 ; 1610static constexpr int32_t TABLE_SCORE = 2 ; 1611static constexpr int32_t TABLE_PIECE_ID = 3 ; 1612 1613// Constants for path array 1614static constexpr int32_t PATH_TOKEN_LENGTH = 0 ; 1615static constexpr int32_t PATH_TOKEN_ID = 1 ; 1616static constexpr int32_t PATH_NUM_TOKENS = 2 ; 1617 1618// Score constants 1619static constexpr int32_t INVALID_SCORE = -20000000 ; 1620static constexpr int32_t UNKNOWN_SCORE = -10000000 ; 1621 1622// List of tokens in the vocabulary 1623 std::vector < std::string > tokens_ ; 1624 1625// Mapping from byte code point to token ID (for byte fallback) 1626 std::vector < llama_token > bytes_ ; 1627 1628// Mapping from piece code to suffix ID 1629 std::unordered_map < int64_t ,int32_t > to_suffix_id_ ; 1630 1631// Flattened table representing the Trie structure 1632// Each row contains: [piece_length, token_id, score, piece_id] 1633 std::vector < std::vector < int32_t >> table_ ; 1634}; 1635 1636struct llm_tokenizer_plamo2_session { 1637llm_tokenizer_plamo2_session (const llm_tokenizer_plamo2 & tokenizer ) :tokenizer (tokenizer ) {} 1638 1639void tokenize (const std::string & text , std::vector < llama_token > & output ) { 1640 std::vector < llama_token > tokens = tokenizer .encode (text ); 1641output .insert (output .end (),tokens .begin (),tokens .end ()); 1642 } 1643 1644private : 1645const llm_tokenizer_plamo2 & tokenizer ; 1646}; 1647 1648// reserved suffix (U+E000) that keeps DNA k-mers distinct from identical 1649// base-vocab BPE tokens (e.g. CCCCCC) in token_to_id; erased from id_to_token 1650// text at load 1651static const std::string dna_kmer_marker = "\xee\x80\x80" ; 1652 1653struct llm_tokenizer_hybriddna_session :llm_tokenizer_bpe_session { 1654llm_tokenizer_hybriddna_session (const llama_vocab & vocab ,const llm_tokenizer_bpe & tokenizer ) :llm_tokenizer_bpe_session {vocab ,tokenizer },vocab {vocab } {} 1655 1656void tokenize (const std::string & text , std::vector < llama_token > & output )override { 1657static const std::string open_tag = "<dna>" ; 1658static const std::string close_tag = "</dna>" ; 1659 1660const auto dna_begin_id = vocab .text_to_token (open_tag ); 1661const auto dna_end_id = vocab .text_to_token (close_tag ); 1662const auto dna_oov_id = vocab .text_to_token ("<oov>" ); 1663 1664// Fall back to plain BPE if the DNA pieces aren't in the vocab. 1665if (dna_begin_id == LLAMA_TOKEN_NULL || dna_end_id == LLAMA_TOKEN_NULL || dna_oov_id == LLAMA_TOKEN_NULL ) { 1666 llm_tokenizer_bpe_session::tokenize (text ,output ); 1667return ; 1668 } 1669 1670const size_t k = 6 ; 1671size_t pos = 0 ; 1672 1673while (pos < text .size ()) { 1674const size_t start = text .find (open_tag ,pos ); 1675if (start == std::string::npos ) { 1676if (pos < text .size ()) { 1677 llm_tokenizer_bpe_session::tokenize (text .substr (pos ),output ); 1678 } 1679break ; 1680 } 1681if (start > pos ) { 1682 llm_tokenizer_bpe_session::tokenize (text .substr (pos ,start - pos ),output ); 1683 } 1684output .push_back (dna_begin_id ); 1685 1686const size_t content_start = start + open_tag .size (); 1687const size_t end = text .find (close_tag ,content_start ); 1688const size_t content_end = (end == std::string::npos ) ?text .size () :end ; 1689 1690emit_dna_kmers (text .substr (content_start ,content_end - content_start ),k ,dna_oov_id ,output ); 1691 1692if (end == std::string::npos ) { 1693break ; 1694 } 1695output .push_back (dna_end_id ); 1696pos = end + close_tag .size (); 1697 } 1698 } 1699 1700private : 1701void emit_dna_kmers (const std::string & raw ,size_t k ,llama_token oov_id , std::vector < llama_token > & output ) { 1702 std::string seq = raw ; 1703for (char & c :seq ) { 1704if (c >='a' && c <='z' ) { 1705c = char (c - 32 ); 1706 } 1707 } 1708 1709// k-mers carry the reserved marker suffix; a non-ACGT k-mer simply 1710// isn't in the vocab and falls back to <oov> 1711auto kmer_token = [& ](const std::string & kmer ) { 1712const auto tok = vocab .text_to_token (kmer + dna_kmer_marker ); 1713return tok != LLAMA_TOKEN_NULL ?tok :oov_id ; 1714 }; 1715 1716size_t i = 0 ; 1717for (;i + k <=seq .size ();i += k ) { 1718output .push_back (kmer_token (seq .substr (i ,k ))); 1719 } 1720if (i < seq .size ()) { 1721 std::string kmer = seq .substr (i ); 1722kmer .append (k - kmer .size (),'A' ); 1723output .push_back (kmer_token (kmer )); 1724 } 1725 } 1726 1727const llama_vocab & vocab ; 1728}; 1729 1730struct llm_tokenizer_whitespace_session :llm_tokenizer_bpe_session { 1731llm_tokenizer_whitespace_session (const llama_vocab & vocab ,const llm_tokenizer_bpe & tokenizer ) :llm_tokenizer_bpe_session {vocab ,tokenizer },vocab {vocab } {} 1732 1733void tokenize (const std::string & text , std::vector < llama_token > & output )override { 1734const bool lowercase = vocab .get_normalizer_opts ().lowercase ; 1735 1736 std::string segment ; 1737auto flush = [& ]() { 1738if (!segment .empty ()) { 1739 llm_tokenizer_bpe_session::tokenize (segment ,output ); 1740segment .clear (); 1741 } 1742 }; 1743 1744for (uint32_t cpt :unicode_cpts_from_utf8 (text )) { 1745// drop whitespace 1746if (unicode_cpt_flags_from_cpt (cpt ).is_whitespace ) { 1747flush (); 1748 }else { 1749segment += unicode_cpt_to_utf8 (lowercase ?unicode_tolower (cpt ) :cpt ); 1750 } 1751 } 1752flush (); 1753 } 1754 1755private : 1756const llama_vocab & vocab ; 1757}; 1758 1759// 1760// impl 1761// 1762 1763typedef enum FRAGMENT_BUFFER_VARIANT_TYPE { 1764FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN , 1765FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT 1766}FRAGMENT_BUFFER_VARIANT_TYPE ; 1767 1768struct fragment_buffer_variant { 1769fragment_buffer_variant (llama_token _token ) 1770 : 1771type (FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN ), 1772token (_token ), 1773raw_text (_dummy ), 1774offset (0 ), 1775length (0 ) {} 1776 1777fragment_buffer_variant (const std::string & _raw_text ,int64_t _offset ,int64_t _length ) 1778 : 1779type (FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT ), 1780token ((llama_token )- 1 ), 1781raw_text (_raw_text ), 1782offset (_offset ), 1783length (_length ){ 1784GGML_ASSERT (_offset >=0 ); 1785GGML_ASSERT (_length >=1 ); 1786GGML_ASSERT (offset + length <=raw_text .length ()); 1787 } 1788 1789const FRAGMENT_BUFFER_VARIANT_TYPE type ; 1790const llama_token token ; 1791const std::string _dummy ; 1792const std::string & raw_text ; 1793const uint64_t offset ; 1794const uint64_t length ; 1795}; 1796 1797struct llama_vocab::impl { 1798uint32_t n_token_types = 0 ;// for BERT-style token types 1799 1800 std::string tokenizer_model ; 1801 std::string tokenizer_pre ; 1802 1803enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM ; 1804enum llama_vocab_pre_type pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT ; 1805 1806int max_token_len = 0 ;// used for optimizing longest token search 1807 1808// default LLaMA special tokens 1809// TODO: should we set all of these to LLAMA_TOKEN_NULL? 1810llama_token special_bos_id = 1 ; 1811llama_token special_eos_id = 2 ; 1812llama_token special_eot_id = LLAMA_TOKEN_NULL ; 1813llama_token special_eom_id = LLAMA_TOKEN_NULL ; 1814llama_token special_unk_id = 0 ; 1815llama_token special_sep_id = LLAMA_TOKEN_NULL ; 1816llama_token special_pad_id = LLAMA_TOKEN_NULL ; 1817llama_token special_mask_id = LLAMA_TOKEN_NULL ; 1818 1819llama_token linefeed_id = 13 ; 1820 1821// fim tokens 1822llama_token special_fim_pre_id = LLAMA_TOKEN_NULL ; 1823llama_token special_fim_suf_id = LLAMA_TOKEN_NULL ; 1824llama_token special_fim_mid_id = LLAMA_TOKEN_NULL ; 1825llama_token special_fim_pad_id = LLAMA_TOKEN_NULL ; 1826llama_token special_fim_rep_id = LLAMA_TOKEN_NULL ;// repo 1827llama_token special_fim_sep_id = LLAMA_TOKEN_NULL ;// file separator 1828 1829// tokenizer flags 1830bool add_space_prefix = false; 1831bool add_bos = false; 1832bool add_eos = false; 1833bool add_sep = false; 1834bool ignore_merges = false; 1835bool clean_spaces = false;// clean_up_tokenization_spaces 1836bool remove_extra_whitespaces = false; 1837bool escape_whitespaces = true; 1838bool treat_whitespace_as_suffix = false; 1839 1840// BertNormalizer options 1841 llama_vocab::normalizer_options normalizer_opts ; 1842 1843 std::unordered_map < std::string ,llama_token > token_to_id ; 1844 std::vector < token_data > id_to_token ; 1845 1846 std::vector < llama_token > cache_special_tokens ; 1847 std::vector < std::string > cache_token_to_piece ;// llama_token_to_piece(special = true); 1848struct pair_hash { 1849size_t operator()(const std::pair < std::string , std::string > & p )const { 1850return std::hash < std::string > {}(p .first ) ^//create some hash for pair 1851 (std::hash < std::string > {}(p .second ) <<1 ); 1852 } 1853 }; 1854 std::unordered_map < std::pair < std::string , std::string > ,int ,pair_hash > bpe_ranks ; 1855 1856// set of all tokens that cause "end of generation" 1857 std::set < llama_token > special_eog_ids ; 1858 1859 std::vector < llama_token > suppress_tokens ; 1860 1861 std::unique_ptr < llm_tokenizer > tokenizer ; 1862 1863 std::vector < char > precompiled_charsmap ; 1864 1865impl (const llama_vocab & vocab ) :vocab (vocab ) { 1866 } 1867 1868 ~impl ()= default ; 1869 1870void load (llama_model_loader & ml ,const LLM_KV & kv ); 1871 1872enum llama_vocab_type get_type ()const ; 1873 1874 std::string type_name ()const ; 1875 1876bool is_normal (llama_token id )const ; 1877bool is_unknown (llama_token id )const ; 1878bool is_control (llama_token id )const ; 1879bool is_byte (llama_token id )const ; 1880bool is_user_defined (llama_token id )const ; 1881bool is_unused (llama_token id )const ; 1882bool is_eog (llama_token id )const ; 1883 1884uint8_t token_to_byte (llama_token id )const ; 1885 1886llama_token_attr token_get_attr (llama_token id )const ; 1887 1888void init_tokenizer (enum llama_vocab_type type ); 1889 1890void tokenizer_st_partition (std::forward_list < fragment_buffer_variant > & buffer ,bool parse_special )const ; 1891 1892 std::string token_to_piece_for_cache ( 1893llama_token token , 1894bool special )const ; 1895 1896 1897 std::vector < llama_token > tokenize ( 1898const std::string & raw_text , 1899bool add_special , 1900bool parse_special = false)const ; 1901 1902int32_t tokenize ( 1903const char * text , 1904int32_t text_len , 1905llama_token * tokens , 1906int32_t n_tokens_max , 1907bool add_special , 1908bool parse_special )const ; 1909 1910// does not write null-terminator to buf 1911int32_t token_to_piece ( 1912llama_token token , 1913char * buf , 1914int32_t length , 1915int32_t lstrip , 1916bool special )const ; 1917 1918// use cached data 1919const std::string & token_to_piece (llama_token token )const ; 1920 1921int32_t detokenize ( 1922const llama_token * tokens , 1923int32_t n_tokens , 1924char * text , 1925int32_t text_len_max , 1926bool remove_special , 1927bool unparse_special )const ; 1928 1929 std::string detokenize ( 1930const std::vector < llama_token > & tokens , 1931bool special )const ; 1932 1933void print_info ()const ; 1934 1935private : 1936const llama_vocab & vocab ; 1937}; 1938 1939void llama_vocab::impl::load (llama_model_loader & ml ,const LLM_KV & kv ) { 1940struct gguf_context * ctx = ml .metadata ; 1941 1942// determine vocab type 1943 { 1944ml .get_key (LLM_KV_TOKENIZER_MODEL ,tokenizer_model ); 1945ml .get_key (LLM_KV_TOKENIZER_PRE ,tokenizer_pre , false); 1946 1947ml .get_key (LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT ,n_token_types , false); 1948 1949if (tokenizer_model == "no_vocab" || tokenizer_model == "none" ) { 1950type = LLAMA_VOCAB_TYPE_NONE ; 1951 1952// default special tokens 1953special_bos_id = LLAMA_TOKEN_NULL ; 1954special_eos_id = LLAMA_TOKEN_NULL ; 1955special_unk_id = LLAMA_TOKEN_NULL ; 1956special_sep_id = LLAMA_TOKEN_NULL ; 1957special_pad_id = LLAMA_TOKEN_NULL ; 1958special_mask_id = LLAMA_TOKEN_NULL ; 1959linefeed_id = LLAMA_TOKEN_NULL ; 1960 1961// read vocab size from metadata 1962uint32_t n_tokens = 0 ; 1963if (ml .get_key (LLM_KV_VOCAB_SIZE ,n_tokens , false)) { 1964LLAMA_LOG_WARN ("%s: adding %u dummy tokens\n" ,__func__ ,n_tokens ); 1965id_to_token .resize (n_tokens ); 1966 } 1967 1968return ; 1969 } 1970 1971if (tokenizer_model == "llama" ) { 1972type = LLAMA_VOCAB_TYPE_SPM ; 1973 1974// default special tokens 1975special_bos_id = 1 ; 1976special_eos_id = 2 ; 1977special_unk_id = 0 ; 1978special_sep_id = LLAMA_TOKEN_NULL ; 1979special_pad_id = LLAMA_TOKEN_NULL ; 1980special_mask_id = LLAMA_TOKEN_NULL ; 1981 }else if (tokenizer_model == "bert" ) { 1982type = LLAMA_VOCAB_TYPE_WPM ; 1983 1984// default special tokens 1985special_bos_id = 101 ; 1986special_eos_id = LLAMA_TOKEN_NULL ; 1987special_unk_id = 100 ; 1988special_sep_id = 102 ; 1989special_pad_id = 0 ; 1990special_mask_id = 103 ; 1991 1992add_sep = true; 1993 }else if (tokenizer_model == "gpt2" || tokenizer_model == "hybriddna" || tokenizer_model == "whitespace" ) { 1994type = LLAMA_VOCAB_TYPE_BPE ; 1995 1996// read bpe merges and populate bpe ranks 1997const int merges_keyidx = gguf_find_key (ctx ,kv (LLM_KV_TOKENIZER_MERGES ).c_str ()); 1998// Kimi-K2 uses custom tokenization without traditional BPE merges 1999const bool is_kimi_k2 = (tokenizer_pre == "kimi-k2" ); 2000 2001if (merges_keyidx == -1 ) { 2002if (!is_kimi_k2 ) { 2003throw std::runtime_error ("cannot find tokenizer merges in model file\n" ); 2004 } 2005// Kimi-K2 doesn't need merges, skip 2006LLAMA_LOG_INFO ("%s: Kimi-K2 tokenizer detected, skipping BPE merges\n" ,__func__ ); 2007 }else { 2008if (gguf_get_kv_type (ctx ,merges_keyidx )!= GGUF_TYPE_ARRAY || 2009gguf_get_arr_type (ctx ,merges_keyidx )!= GGUF_TYPE_STRING ) { 2010throw std::runtime_error (format ("invalid gguf type for %s" ,kv (LLM_KV_TOKENIZER_MERGES ).c_str ())); 2011 } 2012const int n_merges = gguf_get_arr_n (ctx ,merges_keyidx ); 2013for (int i = 0 ;i < n_merges ;i ++ ) { 2014const std::string word = gguf_get_arr_str (ctx ,merges_keyidx ,i ); 2015//GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0); 2016 2017 std::string first ; 2018 std::string second ; 2019 2020const size_t pos = word .find (' ' ,1 ); 2021 2022if (pos != std::string::npos ) { 2023first = word .substr (0 ,pos ); 2024second = word .substr (pos + 1 ); 2025 } 2026 2027bpe_ranks .emplace (std::make_pair (first ,second ),i ); 2028 } 2029 } 2030 2031// default special tokens 2032special_bos_id = 11 ; 2033special_eos_id = 11 ; 2034special_unk_id = LLAMA_TOKEN_NULL ; 2035special_sep_id = LLAMA_TOKEN_NULL ; 2036special_pad_id = LLAMA_TOKEN_NULL ; 2037special_mask_id = LLAMA_TOKEN_NULL ; 2038 }else if (tokenizer_model == "t5" ) { 2039type = LLAMA_VOCAB_TYPE_UGM ; 2040 2041// default special tokens 2042special_bos_id = LLAMA_TOKEN_NULL ; 2043special_eos_id = 1 ; 2044special_unk_id = 2 ; 2045special_sep_id = LLAMA_TOKEN_NULL ; 2046special_pad_id = 0 ; 2047special_mask_id = LLAMA_TOKEN_NULL ; 2048 2049const int precompiled_charsmap_keyidx = gguf_find_key (ctx ,kv (LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP ).c_str ()); 2050if (precompiled_charsmap_keyidx != -1 ) { 2051if (gguf_get_kv_type (ctx ,precompiled_charsmap_keyidx )!= GGUF_TYPE_ARRAY ) { 2052throw std::runtime_error (format ("invalid gguf type for %s" ,kv (LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP ).c_str ())); 2053 } 2054const gguf_type pc_type = gguf_get_arr_type (ctx ,precompiled_charsmap_keyidx ); 2055if (pc_type != GGUF_TYPE_INT8 && pc_type != GGUF_TYPE_UINT8 ) { 2056throw std::runtime_error (format ("invalid gguf type for %s" ,kv (LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP ).c_str ())); 2057 } 2058 2059const size_t n_precompiled_charsmap = gguf_get_arr_n (ctx ,precompiled_charsmap_keyidx ); 2060const char * pc = (const char * )gguf_get_arr_data (ctx ,precompiled_charsmap_keyidx ); 2061precompiled_charsmap .assign (pc ,pc + n_precompiled_charsmap ); 2062if (precompiled_charsmap .size ()< sizeof (uint32_t )) { 2063throw std::runtime_error ("precompiled_charsmap too small for xcda_blob_size header!" ); 2064 } 2065uint32_t * xcda_blob_size = (uint32_t * )& precompiled_charsmap [0 ]; 2066#if defined(__BYTE_ORDER__ )&& defined(__ORDER_BIG_ENDIAN__ )&& __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ 2067* xcda_blob_size = __builtin_bswap32 (* xcda_blob_size ); 2068#endif 2069if (* xcda_blob_size + sizeof (uint32_t ) >=precompiled_charsmap .size ()) { 2070throw std::runtime_error ("Index out of array bounds in precompiled charsmap!" ); 2071 } 2072#if defined(__BYTE_ORDER__ )&& defined(__ORDER_BIG_ENDIAN__ )&& __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ 2073// correct endianness of data in precompiled_charsmap binary blob 2074size_t xcda_array_size = * xcda_blob_size /sizeof (uint32_t ); 2075uint32_t * xcda_array = (uint32_t * )& precompiled_charsmap [sizeof (uint32_t )]; 2076for (size_t i = 0 ;i < xcda_array_size ;++ i ) { 2077xcda_array [i ]= __builtin_bswap32 (xcda_array [i ]); 2078 } 2079#endif 2080 } 2081 }else if (tokenizer_model == "rwkv" ) { 2082type = LLAMA_VOCAB_TYPE_RWKV ; 2083 2084// default special tokens 2085special_bos_id = LLAMA_TOKEN_NULL ; 2086special_eos_id = LLAMA_TOKEN_NULL ; 2087special_unk_id = LLAMA_TOKEN_NULL ; 2088special_sep_id = LLAMA_TOKEN_NULL ; 2089special_pad_id = LLAMA_TOKEN_NULL ; 2090 }else if (tokenizer_model == "test" ) { 2091type = LLAMA_VOCAB_TYPE_TEST ; 2092 2093// default special tokens 2094special_bos_id = LLAMA_TOKEN_NULL ; 2095special_eos_id = LLAMA_TOKEN_NULL ; 2096special_unk_id = LLAMA_TOKEN_NULL ; 2097special_sep_id = LLAMA_TOKEN_NULL ; 2098special_pad_id = LLAMA_TOKEN_NULL ; 2099special_mask_id = LLAMA_TOKEN_NULL ; 2100 }else if (tokenizer_model == "plamo2" ) { 2101type = LLAMA_VOCAB_TYPE_PLAMO2 ; 2102 2103// PLaMo-2 default special tokens (these will be overridden by model config) 2104special_bos_id = 1 ;// <|plamo:bos|> 2105special_eos_id = 2 ;// <|plamo:eos|> 2106special_unk_id = 0 ;// <|plamo:unk|> 2107special_sep_id = LLAMA_TOKEN_NULL ; 2108special_pad_id = 3 ;// <|plamo:pad|> 2109special_mask_id = LLAMA_TOKEN_NULL ; 2110 }else if (tokenizer_model == "gemma4" ) { 2111type = LLAMA_VOCAB_TYPE_BPE ; 2112 2113// read bpe merges and populate bpe ranks 2114const int merges_keyidx = gguf_find_key (ctx ,kv (LLM_KV_TOKENIZER_MERGES ).c_str ()); 2115if (merges_keyidx == -1 ) { 2116throw std::runtime_error ("cannot find tokenizer merges in model file\n" ); 2117 } 2118 { 2119if (gguf_get_kv_type (ctx ,merges_keyidx )!= GGUF_TYPE_ARRAY || 2120gguf_get_arr_type (ctx ,merges_keyidx )!= GGUF_TYPE_STRING ) { 2121throw std::runtime_error (format ("invalid gguf type for %s" ,kv (LLM_KV_TOKENIZER_MERGES ).c_str ())); 2122 } 2123const int n_merges = gguf_get_arr_n (ctx ,merges_keyidx ); 2124for (int i = 0 ;i < n_merges ;i ++ ) { 2125const std::string word = gguf_get_arr_str (ctx ,merges_keyidx ,i ); 2126 2127 std::string first ; 2128 std::string second ; 2129 2130const size_t pos = word .find (' ' ,1 ); 2131 2132if (pos != std::string::npos ) { 2133first = word .substr (0 ,pos ); 2134second = word .substr (pos + 1 ); 2135 } 2136 2137bpe_ranks .emplace (std::make_pair (first ,second ),i ); 2138 } 2139 } 2140 2141// default special tokens (to be read from GGUF) 2142special_bos_id = LLAMA_TOKEN_NULL ; 2143special_eos_id = LLAMA_TOKEN_NULL ; 2144special_unk_id = LLAMA_TOKEN_NULL ; 2145special_sep_id = LLAMA_TOKEN_NULL ; 2146special_pad_id = LLAMA_TOKEN_NULL ; 2147special_mask_id = LLAMA_TOKEN_NULL ; 2148 2149tokenizer_pre = "gemma4" ; 2150 }else { 2151throw std::runtime_error (format ("unknown tokenizer: '%s'" ,tokenizer_model .c_str ())); 2152 } 2153 2154// for now, only BPE models have pre-tokenizers 2155if (type == LLAMA_VOCAB_TYPE_BPE ) { 2156add_space_prefix = false; 2157escape_whitespaces = false; 2158clean_spaces = true; 2159if (tokenizer_pre .empty ()) { 2160LLAMA_LOG_WARN ("%s: missing pre-tokenizer type, using: 'default'\n" ,__func__ ); 2161LLAMA_LOG_WARN ("%s: \n" ,__func__ ); 2162LLAMA_LOG_WARN ("%s: ************************************ \n" ,__func__ ); 2163LLAMA_LOG_WARN ("%s: GENERATION QUALITY WILL BE DEGRADED! \n" ,__func__ ); 2164LLAMA_LOG_WARN ("%s: CONSIDER REGENERATING THE MODEL \n" ,__func__ ); 2165LLAMA_LOG_WARN ("%s: ************************************ \n" ,__func__ ); 2166LLAMA_LOG_WARN ("%s: \n" ,__func__ ); 2167pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT ; 2168 }else if (tokenizer_pre == "default" ) { 2169pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT ; 2170 }else if (tokenizer_pre == "minicpm5" ) { 2171pre_type = LLAMA_VOCAB_PRE_TYPE_MINICPM5 ; 2172ignore_merges = true; 2173 }else if ( 2174tokenizer_pre == "llama3" || 2175tokenizer_pre == "llama-v3" || 2176tokenizer_pre == "llama-bpe" || 2177tokenizer_pre == "falcon3" || 2178tokenizer_pre == "falcon-h1" || 2179tokenizer_pre == "pixtral" || 2180tokenizer_pre == "midm-2.0" || 2181tokenizer_pre == "lfm2" || 2182tokenizer_pre == "jina-v5-nano" ) { 2183pre_type = LLAMA_VOCAB_PRE_TYPE_LLAMA3 ; 2184ignore_merges = true; 2185add_bos = true; 2186 }else if ( 2187tokenizer_pre == "deepseek-llm" ) { 2188pre_type = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM ; 2189clean_spaces = false; 2190 }else if ( 2191tokenizer_pre == "deepseek-coder" ) { 2192pre_type = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER ; 2193clean_spaces = false; 2194 }else if ( 2195tokenizer_pre == "deepseek-v3" ) { 2196pre_type = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK3_LLM ; 2197clean_spaces = false; 2198 }else if ( 2199tokenizer_pre == "spark2_5" ) { 2200pre_type = LLAMA_VOCAB_PRE_TYPE_SPARK2_5 ; 2201clean_spaces = false; 2202 }else if ( 2203tokenizer_pre == "youtu" ) { 2204pre_type = LLAMA_VOCAB_PRE_TYPE_YOUTU ; 2205clean_spaces = false; 2206ignore_merges = true; 2207 }else if ( 2208tokenizer_pre == "falcon" ) { 2209pre_type = LLAMA_VOCAB_PRE_TYPE_FALCON ; 2210 }else if ( 2211tokenizer_pre == "mpt" ) { 2212pre_type = LLAMA_VOCAB_PRE_TYPE_MPT ; 2213 }else if ( 2214tokenizer_pre == "starcoder" ) { 2215pre_type = LLAMA_VOCAB_PRE_TYPE_STARCODER ; 2216 }else if ( 2217tokenizer_pre == "gpt-2" || 2218tokenizer_pre == "phi-2" || 2219tokenizer_pre == "jina-es" || 2220tokenizer_pre == "jina-de" || 2221tokenizer_pre == "gigachat" || 2222tokenizer_pre == "jina-v2-es" || 2223tokenizer_pre == "jina-v2-de" || 2224tokenizer_pre == "a.x-4.0" || 2225tokenizer_pre == "mellum" || 2226tokenizer_pre == "modern-bert" ) { 2227pre_type = LLAMA_VOCAB_PRE_TYPE_GPT2 ; 2228 }else if ( 2229tokenizer_pre == "jais-2" ) { 2230pre_type = LLAMA_VOCAB_PRE_TYPE_JAIS2 ; 2231 }else if ( 2232tokenizer_pre == "gemma4" || 2233tokenizer_pre == "granite-embed-multi-311m" ) { 2234pre_type = LLAMA_VOCAB_PRE_TYPE_GEMMA4 ; 2235escape_whitespaces = true; 2236 }else if ( 2237tokenizer_pre == "sarvam-moe" ) { 2238pre_type = LLAMA_VOCAB_PRE_TYPE_SARVAM_MOE ; 2239escape_whitespaces = true; 2240clean_spaces = false; 2241 }else if ( 2242tokenizer_pre == "jina-v1-en" || 2243tokenizer_pre == "jina-v2-code" || 2244tokenizer_pre == "roberta-bpe" ) { 2245pre_type = LLAMA_VOCAB_PRE_TYPE_GPT2 ; 2246add_sep = true; 2247 }else if ( 2248tokenizer_pre == "whitespace" ) { 2249pre_type = LLAMA_VOCAB_PRE_TYPE_WHITESPACE ; 2250normalizer_opts .lowercase = false; 2251 }else if ( 2252tokenizer_pre == "refact" ) { 2253pre_type = LLAMA_VOCAB_PRE_TYPE_REFACT ; 2254 }else if ( 2255tokenizer_pre == "command-r" ) { 2256pre_type = LLAMA_VOCAB_PRE_TYPE_COMMAND_R ; 2257clean_spaces = false; 2258 }else if ( 2259tokenizer_pre == "qwen2" || 2260tokenizer_pre == "deepseek-r1-qwen" || 2261tokenizer_pre == "kormo" || 2262tokenizer_pre == "f2llmv2" ) { 2263pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN2 ; 2264clean_spaces = false; 2265 }else if ( 2266tokenizer_pre == "qwen35" ) { 2267pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN35 ; 2268clean_spaces = false; 2269 }else if ( 2270tokenizer_pre == "stablelm2" ) { 2271pre_type = LLAMA_VOCAB_PRE_TYPE_STABLELM2 ; 2272 }else if ( 2273tokenizer_pre == "olmo" ) { 2274pre_type = LLAMA_VOCAB_PRE_TYPE_OLMO ; 2275 }else if ( 2276tokenizer_pre == "dbrx" ) { 2277pre_type = LLAMA_VOCAB_PRE_TYPE_DBRX ; 2278 }else if ( 2279tokenizer_pre == "smaug-bpe" ) { 2280pre_type = LLAMA_VOCAB_PRE_TYPE_SMAUG ; 2281 }else if ( 2282tokenizer_pre == "poro-chat" ) { 2283pre_type = LLAMA_VOCAB_PRE_TYPE_PORO ; 2284clean_spaces = false; 2285 }else if ( 2286tokenizer_pre == "glm4" || 2287tokenizer_pre == "chatglm-bpe" ) { 2288pre_type = LLAMA_VOCAB_PRE_TYPE_CHATGLM4 ; 2289special_bos_id = LLAMA_TOKEN_NULL ; 2290 }else if ( 2291tokenizer_pre == "viking" ) { 2292pre_type = LLAMA_VOCAB_PRE_TYPE_VIKING ; 2293clean_spaces = false; 2294 }else if ( 2295tokenizer_pre == "jais" ) { 2296pre_type = LLAMA_VOCAB_PRE_TYPE_JAIS ; 2297 }else if ( 2298tokenizer_pre == "tekken" ) { 2299pre_type = LLAMA_VOCAB_PRE_TYPE_TEKKEN ; 2300clean_spaces = false; 2301ignore_merges = true; 2302add_bos = true; 2303 }else if ( 2304tokenizer_pre == "smollm" ) { 2305pre_type = LLAMA_VOCAB_PRE_TYPE_SMOLLM ; 2306clean_spaces = false; 2307 }else if ( 2308tokenizer_pre == "codeshell" ) { 2309pre_type = LLAMA_VOCAB_PRE_TYPE_CODESHELL ; 2310 }else if ( 2311tokenizer_pre == "bloom" ) { 2312pre_type = LLAMA_VOCAB_PRE_TYPE_BLOOM ; 2313 }else if ( 2314tokenizer_pre == "gpt3-finnish" ) { 2315pre_type = LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH ; 2316 }else if ( 2317tokenizer_pre == "exaone" ) { 2318pre_type = LLAMA_VOCAB_PRE_TYPE_EXAONE ; 2319 }else if ( 2320tokenizer_pre == "exaone4" ) { 2321pre_type = LLAMA_VOCAB_PRE_TYPE_GPT2 ; 2322 }else if ( 2323tokenizer_pre == "exaone-moe" ) { 2324pre_type = LLAMA_VOCAB_PRE_TYPE_EXAONE_MOE ; 2325 }else if ( 2326tokenizer_pre == "chameleon" ) { 2327pre_type = LLAMA_VOCAB_PRE_TYPE_CHAMELEON ; 2328add_bos = true; 2329clean_spaces = false; 2330 }else if ( 2331tokenizer_pre == "minerva-7b" ) { 2332pre_type = LLAMA_VOCAB_PRE_TYPE_MINERVA ; 2333 }else if ( 2334tokenizer_pre == "megrez" ) { 2335pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN2 ; 2336 }else if ( 2337tokenizer_pre == "gpt-4o" || 2338tokenizer_pre == "llama4" || 2339tokenizer_pre == "kanana2" || 2340tokenizer_pre == "talkie" ) { 2341pre_type = LLAMA_VOCAB_PRE_TYPE_GPT4O ; 2342clean_spaces = false; 2343 }else if ( 2344tokenizer_pre == "granite-embed-multi-97m" ) { 2345pre_type = LLAMA_VOCAB_PRE_TYPE_GRANITE_EMB_MULTI ; 2346clean_spaces = false; 2347ignore_merges = true; 2348 }else if ( 2349tokenizer_pre == "tiny_aya" || 2350tokenizer_pre == "cohere2moe" ) { 2351pre_type = LLAMA_VOCAB_PRE_TYPE_TINY_AYA ; 2352clean_spaces = false; 2353 }else if ( 2354tokenizer_pre == "superbpe" ) { 2355pre_type = LLAMA_VOCAB_PRE_TYPE_SUPERBPE ; 2356clean_spaces = false; 2357 }else if ( 2358tokenizer_pre == "trillion" ) { 2359pre_type = LLAMA_VOCAB_PRE_TYPE_TRILLION ; 2360clean_spaces = false; 2361 }else if ( 2362tokenizer_pre == "granite-docling" ) { 2363pre_type = LLAMA_VOCAB_PRE_TYPE_GRANITE_DOCLING ; 2364clean_spaces = false; 2365 }else if ( 2366tokenizer_pre == "bailingmoe" || 2367tokenizer_pre == "bailingmoe2" || 2368tokenizer_pre == "llada-moe" ) { 2369pre_type = LLAMA_VOCAB_PRE_TYPE_BAILINGMOE ; 2370clean_spaces = false; 2371 }else if ( 2372tokenizer_pre == "seed-coder" ) { 2373pre_type = LLAMA_VOCAB_PRE_TYPE_SEED_CODER ; 2374clean_spaces = false; 2375 }else if ( 2376tokenizer_pre == "hunyuan" ) { 2377pre_type = LLAMA_VOCAB_PRE_TYPE_HUNYUAN ; 2378clean_spaces = false; 2379 }else if ( 2380tokenizer_pre == "hunyuan-dense" ) { 2381pre_type = LLAMA_VOCAB_PRE_TYPE_HUNYUAN_DENSE ; 2382clean_spaces = false; 2383 }else if ( 2384tokenizer_pre == "hy_v4" ) { 2385pre_type = LLAMA_VOCAB_PRE_TYPE_HY_V4 ; 2386clean_spaces = false; 2387 }else if ( 2388tokenizer_pre == "joyai-llm" ) { 2389pre_type = LLAMA_VOCAB_PRE_TYPE_JOYAI_LLM ; 2390clean_spaces = false; 2391 }else if ( 2392tokenizer_pre == "kimi-k2" ) { 2393pre_type = LLAMA_VOCAB_PRE_TYPE_KIMI_K2 ; 2394clean_spaces = false; 2395 }else if ( 2396tokenizer_pre == "ufakzeka" ) { 2397pre_type = LLAMA_VOCAB_PRE_TYPE_UFAKZEKA ; 2398clean_spaces = false; 2399 }else if ( 2400tokenizer_pre == "grok-2" ) { 2401pre_type = LLAMA_VOCAB_PRE_TYPE_GROK_2 ; 2402clean_spaces = false; 2403 }else if ( 2404tokenizer_pre == "afmoe" ) { 2405pre_type = LLAMA_VOCAB_PRE_TYPE_AFMOE ; 2406clean_spaces = false; 2407 }else if ( 2408tokenizer_pre == "laguna" ) { 2409pre_type = LLAMA_VOCAB_PRE_TYPE_LAGUNA ; 2410clean_spaces = false; 2411 }else if ( 2412tokenizer_pre == "minimax-m2" ) { 2413pre_type = LLAMA_VOCAB_PRE_TYPE_MINIMAX_M2 ; 2414clean_spaces = false; 2415 }else if ( 2416tokenizer_pre == "solar-open" ) { 2417pre_type = LLAMA_VOCAB_PRE_TYPE_SOLAR_OPEN ; 2418clean_spaces = false; 2419 }else if ( 2420tokenizer_pre == "mellum2" ) { 2421pre_type = LLAMA_VOCAB_PRE_TYPE_MELLUM2 ; 2422 }else { 2423throw std::runtime_error (format ("unknown pre-tokenizer type: '%s'" ,tokenizer_pre .c_str ())); 2424 } 2425 }else if (type == LLAMA_VOCAB_TYPE_SPM ) { 2426pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT ; 2427add_space_prefix = true; 2428clean_spaces = false; 2429add_bos = true; 2430add_eos = false; 2431 }else if (type == LLAMA_VOCAB_TYPE_WPM ) { 2432pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT ; 2433add_space_prefix = false; 2434clean_spaces = true; 2435add_bos = true; 2436add_eos = false; 2437add_sep = true; 2438 }else if (type == LLAMA_VOCAB_TYPE_UGM ) { 2439pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT ; 2440add_bos = false; 2441add_eos = true; 2442 }else if (type == LLAMA_VOCAB_TYPE_RWKV ) { 2443pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT ; 2444add_space_prefix = false; 2445clean_spaces = false; 2446add_bos = false; 2447add_eos = false; 2448 }else { 2449pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT ; 2450 } 2451 2452ml .get_key (LLM_KV_TOKENIZER_ADD_PREFIX ,add_space_prefix , false); 2453ml .get_key (LLM_KV_TOKENIZER_REMOVE_EXTRA_WS ,remove_extra_whitespaces , false); 2454 } 2455 2456const int token_idx = gguf_find_key (ctx ,kv (LLM_KV_TOKENIZER_LIST ).c_str ()); 2457if (token_idx == -1 ) { 2458throw std::runtime_error ("cannot find tokenizer vocab in model file\n" ); 2459 } 2460 2461if (gguf_get_kv_type (ctx ,token_idx )!= GGUF_TYPE_ARRAY || 2462gguf_get_arr_type (ctx ,token_idx )!= GGUF_TYPE_STRING ) { 2463throw std::runtime_error (format ("invalid gguf type for %s" ,kv (LLM_KV_TOKENIZER_LIST ).c_str ())); 2464 } 2465 2466const uint32_t n_tokens = gguf_get_arr_n (ctx ,token_idx ); 2467 2468const float * scores = nullptr ; 2469const int * iscores = nullptr ; 2470const int score_idx = gguf_find_key (ctx ,kv (LLM_KV_TOKENIZER_SCORES ).c_str ()); 2471if (score_idx != -1 ) { 2472const gguf_type kv_type = gguf_get_kv_type (ctx ,score_idx ); 2473const gguf_type arr_type = kv_type == GGUF_TYPE_ARRAY ?gguf_get_arr_type (ctx ,score_idx ) :GGUF_TYPE_COUNT ; 2474if (arr_type != GGUF_TYPE_INT32 && 2475arr_type != GGUF_TYPE_FLOAT32 ) { 2476throw std::runtime_error (format ("invalid gguf type for %s" ,kv (LLM_KV_TOKENIZER_SCORES ).c_str ())); 2477 } 2478const uint32_t n_scores = gguf_get_arr_n (ctx ,score_idx ); 2479if (n_scores < n_tokens ) { 2480throw std::runtime_error ("Index out of array bounds for scores (" + std::to_string (n_scores )+ " < " + std::to_string (n_tokens )+ ")\n" ); 2481 } 2482if (arr_type == GGUF_TYPE_INT32 ) { 2483iscores = (const int * )gguf_get_arr_data (ctx ,score_idx ); 2484 }else { 2485scores = (const float * )gguf_get_arr_data (ctx ,score_idx ); 2486 } 2487 } 2488 2489const int * toktypes = nullptr ; 2490const int toktype_idx = gguf_find_key (ctx ,kv (LLM_KV_TOKENIZER_TOKEN_TYPE ).c_str ()); 2491if (toktype_idx != -1 ) { 2492if (gguf_get_kv_type (ctx ,toktype_idx )!= GGUF_TYPE_ARRAY || 2493gguf_get_arr_type (ctx ,toktype_idx )!= GGUF_TYPE_INT32 ) { 2494throw std::runtime_error (format ("invalid gguf type for %s" ,kv (LLM_KV_TOKENIZER_TOKEN_TYPE ).c_str ())); 2495 } 2496const uint32_t n_toktypes = gguf_get_arr_n (ctx ,toktype_idx ); 2497if (n_toktypes < n_tokens ) { 2498throw std::runtime_error ("Index out of array bounds for toktypes (" + std::to_string (n_toktypes )+ " < " + std::to_string (n_tokens )+ ")\n" ); 2499 } 2500toktypes = (const int * )gguf_get_arr_data (ctx ,toktype_idx ); 2501 } 2502 2503id_to_token .resize (n_tokens ); 2504 2505for (uint32_t i = 0 ;i < n_tokens ;i ++ ) { 2506 std::string word = gguf_get_arr_str (ctx ,token_idx ,i ); 2507if (word .empty ()) { 2508LLAMA_LOG_WARN ("%s: empty token at index %u\n" ,__func__ ,i ); 2509word = "[EMPTY_" + std::to_string (i )+ "]" ; 2510 } 2511 2512token_to_id [word ]= i ; 2513max_token_len = std::max (max_token_len , (int )word .size ()); 2514 2515auto & token_data = id_to_token [i ]; 2516token_data .text = std::move (word ); 2517if (scores ) { 2518token_data .score = scores [i ]; 2519 }else if (iscores ) { 2520token_data .score = static_cast < float > (iscores [i ]); 2521 }else { 2522token_data .score = 0.0f ; 2523 } 2524token_data .attr = LLAMA_TOKEN_ATTR_NORMAL ; 2525 2526if (toktypes ) {//TODO: remove, required until per token attributes are available from GGUF file 2527switch (toktypes [i ]) { 2528case LLAMA_TOKEN_TYPE_UNKNOWN :token_data .attr = LLAMA_TOKEN_ATTR_UNKNOWN ;break ; 2529case LLAMA_TOKEN_TYPE_UNUSED :token_data .attr = LLAMA_TOKEN_ATTR_UNUSED ;break ; 2530case LLAMA_TOKEN_TYPE_NORMAL :token_data .attr = LLAMA_TOKEN_ATTR_NORMAL ;break ; 2531case LLAMA_TOKEN_TYPE_CONTROL :token_data .attr = LLAMA_TOKEN_ATTR_CONTROL ;break ; 2532case LLAMA_TOKEN_TYPE_USER_DEFINED :token_data .attr = LLAMA_TOKEN_ATTR_USER_DEFINED ;break ; 2533case LLAMA_TOKEN_TYPE_BYTE :token_data .attr = LLAMA_TOKEN_ATTR_BYTE ;break ; 2534case LLAMA_TOKEN_TYPE_UNDEFINED :token_data .attr = LLAMA_TOKEN_ATTR_UNDEFINED ;break ; 2535default :token_data .attr = LLAMA_TOKEN_ATTR_UNDEFINED ;break ; 2536 } 2537 } 2538 } 2539GGML_ASSERT (id_to_token .size ()== token_to_id .size ()); 2540 2541// hybriddna: the marker suffix kept k-mer ids distinct in token_to_id; erase 2542// it from id_to_token so the k-mers detokenize to the bare DNA sequence. The 2543// k-mers are the block right after <oov>, so only scan from there. 2544if (tokenizer_model == "hybriddna" ) { 2545const auto idx = token_to_id .find ("<oov>" ); 2546if (idx != token_to_id .end ()) { 2547auto it = id_to_token .begin ()+ idx -> second + 1 ; 2548for (;it != id_to_token .end ();++ it ) { 2549 std::string & text = it -> text ; 2550if (text .size ()> dna_kmer_marker .size () 2551&& text .compare (text .size ()- dna_kmer_marker .size (),dna_kmer_marker .size (),dna_kmer_marker )== 0 ) { 2552text .erase (text .size ()- dna_kmer_marker .size ()); 2553 } 2554 } 2555 } 2556 } 2557 2558init_tokenizer (type ); 2559 2560// determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n' 2561if (type == LLAMA_VOCAB_TYPE_SPM ) { 2562try { 2563linefeed_id = vocab .byte_to_token ('\n' ); 2564 }catch (const std::exception & e ) { 2565LLAMA_LOG_WARN ("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead." ,__func__ ,e .what ()); 2566linefeed_id = special_pad_id ; 2567 } 2568 }else if (type == LLAMA_VOCAB_TYPE_WPM ) { 2569linefeed_id = special_pad_id ; 2570 }else if (type == LLAMA_VOCAB_TYPE_RWKV ) { 2571const std::vector < int > ids = tokenize ("\n" , false); 2572GGML_ASSERT (!ids .empty ()&& "model vocab missing newline token" ); 2573linefeed_id = ids [0 ]; 2574 }else { 2575const std::vector < int > ids = tokenize ("\n" , false); 2576 2577//GGML_ASSERT(!ids.empty() && "model vocab missing newline token"); 2578if (ids .empty ()) { 2579LLAMA_LOG_WARN ("%s: model vocab missing newline token, using special_pad_id instead\n" ,__func__ ); 2580linefeed_id = special_pad_id ; 2581 }else { 2582linefeed_id = ids [0 ]; 2583 } 2584 } 2585 2586// special tokens 2587 { 2588const std::vector < std::pair < enum llm_kv ,int32_t &>> special_token_types = { 2589 {LLM_KV_TOKENIZER_BOS_ID ,special_bos_id }, 2590 {LLM_KV_TOKENIZER_EOS_ID ,special_eos_id }, 2591 {LLM_KV_TOKENIZER_EOT_ID ,special_eot_id }, 2592 {LLM_KV_TOKENIZER_EOM_ID ,special_eom_id }, 2593 {LLM_KV_TOKENIZER_UNK_ID ,special_unk_id }, 2594 {LLM_KV_TOKENIZER_SEP_ID ,special_sep_id }, 2595 {LLM_KV_TOKENIZER_PAD_ID ,special_pad_id }, 2596 {LLM_KV_TOKENIZER_MASK_ID ,special_mask_id }, 2597 {LLM_KV_TOKENIZER_FIM_PRE_ID ,special_fim_pre_id }, 2598 {LLM_KV_TOKENIZER_FIM_SUF_ID ,special_fim_suf_id }, 2599 {LLM_KV_TOKENIZER_FIM_MID_ID ,special_fim_mid_id }, 2600 {LLM_KV_TOKENIZER_FIM_PAD_ID ,special_fim_pad_id }, 2601 {LLM_KV_TOKENIZER_FIM_REP_ID ,special_fim_rep_id }, 2602 {LLM_KV_TOKENIZER_FIM_SEP_ID ,special_fim_sep_id }, 2603 2604// deprecated 2605 {LLM_KV_TOKENIZER_PREFIX_ID ,special_fim_pre_id }, 2606 {LLM_KV_TOKENIZER_SUFFIX_ID ,special_fim_suf_id }, 2607 {LLM_KV_TOKENIZER_MIDDLE_ID ,special_fim_mid_id }, 2608 }; 2609 2610for (const auto & it :special_token_types ) { 2611const std::string & key = kv (std::get < 0 > (it )); 2612int32_t & id = std::get < 1 > (it ); 2613 2614if (id >=0 && static_cast < size_t > (id ) >=id_to_token .size ()) { 2615LLAMA_LOG_WARN ("%s: default special token '%s' = %d out of vocab range, disabling\n" , 2616__func__ ,key .c_str (),id ); 2617id = LLAMA_TOKEN_NULL ; 2618 } 2619 2620uint32_t new_id ; 2621if (!ml .get_key (std::get < 0 > (it ),new_id , false)) { 2622continue ; 2623 } 2624if (new_id >=id_to_token .size ()) { 2625LLAMA_LOG_WARN ("%s: bad special token: '%s' = %u, using default id %d\n" , 2626__func__ ,key .c_str (),new_id ,id ); 2627 }else { 2628id = new_id ; 2629 } 2630 } 2631 2632// Handle add_bos, add_eos and add_sep 2633 { 2634bool temp = true; 2635 2636if (ml .get_key (LLM_KV_TOKENIZER_ADD_BOS ,temp , false)) { 2637add_bos = temp ; 2638 } 2639if (ml .get_key (LLM_KV_TOKENIZER_ADD_EOS ,temp , false)) { 2640add_eos = temp ; 2641 } 2642if (ml .get_key (LLM_KV_TOKENIZER_ADD_SEP ,temp , false)) { 2643add_sep = temp ; 2644 } 2645 2646// workaround for Gemma 4 2647// ref: https://github.com/ggml-org/llama.cpp/pull/21500 2648if (pre_type == LLAMA_VOCAB_PRE_TYPE_GEMMA4 && !add_bos ) { 2649add_bos = true; 2650 2651LLAMA_LOG_WARN ("%s: override '%s' to 'true' for Gemma4\n" ,__func__ ,kv (LLM_KV_TOKENIZER_ADD_BOS ).c_str ()); 2652 } 2653 } 2654 2655// BertNormalizer options 2656ml .get_key (LLM_KV_TOKENIZER_NORMALIZER_LOWERCASE ,normalizer_opts .lowercase , false); 2657normalizer_opts .strip_accents = normalizer_opts .lowercase ; 2658ml .get_key (LLM_KV_TOKENIZER_NORMALIZER_STRIP_ACCENTS ,normalizer_opts .strip_accents , false); 2659 2660// suppress tokens 2661 { 2662const int suppress_idx = gguf_find_key (ctx ,kv (LLM_KV_TOKENIZER_SUPPRESS_TOKENS ).c_str ()); 2663if (suppress_idx != -1 ) { 2664if (gguf_get_kv_type (ctx ,suppress_idx )!= GGUF_TYPE_ARRAY || 2665gguf_get_arr_type (ctx ,suppress_idx )!= GGUF_TYPE_INT32 ) { 2666throw std::runtime_error (format ("invalid gguf type for %s" ,kv (LLM_KV_TOKENIZER_SUPPRESS_TOKENS ).c_str ())); 2667 } 2668const int n = gguf_get_arr_n (ctx ,suppress_idx ); 2669const int32_t * data = (const int32_t * )gguf_get_arr_data (ctx ,suppress_idx ); 2670// drop out-of-range ids 2671suppress_tokens .reserve (n ); 2672for (int i = 0 ;i < n ;++ i ) { 2673const int32_t id = data [i ]; 2674if (id >=0 && id < (int )id_to_token .size ()) { 2675suppress_tokens .push_back (id ); 2676 } 2677 } 2678 } 2679 } 2680 2681// auto-detect special tokens by text 2682// TODO: convert scripts should provide these tokens through the KV metadata LLM_KV_TOKENIZER_... 2683// for now, we apply this workaround to find the tokens based on their text 2684 2685for (const auto & t :token_to_id ) { 2686auto & attr = id_to_token [t .second ].attr ; 2687 2688// find EOT token: "<|eot_id|>", "<|im_end|>", "<end_of_turn>", etc. 2689if (special_eot_id == LLAMA_TOKEN_NULL ) { 2690if (false 2691|| t .first == "<|eot_id|>" 2692|| t .first == "<|im_end|>" 2693|| t .first == "<|end|>" 2694|| t .first == "<end_of_turn>" 2695|| t .first == "<|endoftext|>" 2696|| t .first == "<|end_of_text|>" // granite 2697|| t .first == "<EOT>" 2698|| t .first == "_<EOT>" 2699|| t .first == "[EOT]" // Kimi-K2 2700|| t .first == "<|end▁of▁sentence|>" // DeepSeek 2701|| t .first == "<end_of_utterance>" // smoldocling 2702 ) { 2703special_eot_id = t .second ; 2704if ((attr & LLAMA_TOKEN_ATTR_CONTROL )== 0 ) { 2705LLAMA_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" , 2706__func__ ,t .second ,t .first .c_str ()); 2707attr = (llama_token_attr ) (attr |LLAMA_TOKEN_ATTR_CONTROL ); 2708 } 2709 } 2710 } 2711 2712// find EOM token: "<|eom_id|>" 2713if (special_eom_id == LLAMA_TOKEN_NULL ) { 2714if (false 2715|| t .first == "<|eom_id|>" 2716 ) { 2717special_eom_id = t .second ; 2718if ((attr & LLAMA_TOKEN_ATTR_CONTROL )== 0 ) { 2719LLAMA_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" , 2720__func__ ,t .second ,t .first .c_str ()); 2721attr = (llama_token_attr ) (attr |LLAMA_TOKEN_ATTR_CONTROL ); 2722 } 2723 } 2724 } 2725 2726// find FIM_PRE token: "<|fim_prefix|>", "<fim-prefix>", "<PRE>", etc. 2727if (special_fim_pre_id == LLAMA_TOKEN_NULL ) { 2728if (false 2729|| t .first == "<|fim_prefix|>" // Qwen 2730|| t .first == "<fim-prefix>" 2731|| t .first == "<fim_prefix>" // Granite 2732|| t .first == "<|fim▁begin|>" // DeepSeek 2733|| t .first == "<PRE>" 2734|| t .first == "▁<PRE>" // CodeLlama 2735|| t .first == "<|code_prefix|>" // GLM-4.5 2736|| t .first == "<|prefix|>" // Falcon-H1-Tiny-Coder 2737 ) { 2738special_fim_pre_id = t .second ; 2739if ((attr & LLAMA_TOKEN_ATTR_CONTROL )== 0 ) { 2740LLAMA_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" , 2741__func__ ,t .second ,t .first .c_str ()); 2742attr = (llama_token_attr ) (attr |LLAMA_TOKEN_ATTR_CONTROL ); 2743 } 2744 } 2745 } 2746 2747// find FIM_SUF token: "<|fim_suffix|>", "<fim-suffix>", "<SUF>", etc. 2748if (special_fim_suf_id == LLAMA_TOKEN_NULL ) { 2749if (false 2750|| t .first == "<|fim_suffix|>" // Qwen 2751|| t .first == "<fim-suffix>" 2752|| t .first == "<fim_suffix>" // Granite 2753|| t .first == "<|fim▁hole|>" // DeepSeek 2754|| t .first == "<SUF>" 2755|| t .first == "▁<SUF>" // CodeLlama 2756|| t .first == "<|code_suffix|>" // GLM-4.5 2757|| t .first == "<|suffix|>" // Falcon-H1-Tiny-Coder 2758 ) { 2759special_fim_suf_id = t .second ; 2760if ((attr & LLAMA_TOKEN_ATTR_CONTROL )== 0 ) { 2761LLAMA_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" , 2762__func__ ,t .second ,t .first .c_str ()); 2763attr = (llama_token_attr ) (attr |LLAMA_TOKEN_ATTR_CONTROL ); 2764 } 2765 } 2766 } 2767 2768// find FIM_MID token: "<|fim_middle|>", "<fim-middle>", "<MID>", etc. 2769if (special_fim_mid_id == LLAMA_TOKEN_NULL ) { 2770if (false 2771|| t .first == "<|fim_middle|>" // Qwen 2772|| t .first == "<fim-middle>" 2773|| t .first == "<fim_middle>" // Granite 2774|| t .first == "<|fim▁end|>" // DeepSeek 2775|| t .first == "<MID>" 2776|| t .first == "▁<MID>" // CodeLlama 2777|| t .first == "<|code_middle|>" // GLM-4.5 2778|| t .first == "<|middle|>" // Falcon-H1-Tiny-Coder 2779 ) { 2780special_fim_mid_id = t .second ; 2781if ((attr & LLAMA_TOKEN_ATTR_CONTROL )== 0 ) { 2782LLAMA_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" , 2783__func__ ,t .second ,t .first .c_str ()); 2784attr = (llama_token_attr ) (attr |LLAMA_TOKEN_ATTR_CONTROL ); 2785 } 2786 } 2787 } 2788 2789// find FIM_PAD token: "<|fim_pad|>", "<fim-pad>", "<PAD>", etc. 2790if (special_fim_pad_id == LLAMA_TOKEN_NULL ) { 2791if (false 2792|| t .first == "<|fim_pad|>" // Qwen 2793|| t .first == "<fim-pad>" 2794|| t .first == "<fim_pad>" // Granite 2795|| t .first == "<PAD>" 2796|| t .first == "[PAD]" // Kimi-K2 2797 ) { 2798special_fim_pad_id = t .second ; 2799if ((attr & LLAMA_TOKEN_ATTR_CONTROL )== 0 ) { 2800LLAMA_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" , 2801__func__ ,t .second ,t .first .c_str ()); 2802attr = (llama_token_attr ) (attr |LLAMA_TOKEN_ATTR_CONTROL ); 2803 } 2804 } 2805 } 2806 2807// find FIM_REP token: "<|fim_repo|>", "<fim-repo>", "<REP>", etc. 2808if (special_fim_rep_id == LLAMA_TOKEN_NULL ) { 2809if (false 2810|| t .first == "<|fim_repo|>" // Qwen 2811|| t .first == "<|repo_name|>" 2812|| t .first == "<fim-repo>" 2813|| t .first == "<REPO>" 2814|| t .first == "<reponame>" // Granite 2815 ) { 2816special_fim_rep_id = t .second ; 2817if ((attr & LLAMA_TOKEN_ATTR_CONTROL )== 0 ) { 2818LLAMA_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" , 2819__func__ ,t .second ,t .first .c_str ()); 2820attr = (llama_token_attr ) (attr |LLAMA_TOKEN_ATTR_CONTROL ); 2821 } 2822 } 2823 } 2824 2825// find FIM_SEP token: "<|file_sep|>" 2826if (special_fim_sep_id == LLAMA_TOKEN_NULL ) { 2827if (false 2828|| t .first == "<|file_sep|>" // Qwen 2829 ) { 2830special_fim_sep_id = t .second ; 2831if ((attr & LLAMA_TOKEN_ATTR_CONTROL )== 0 ) { 2832LLAMA_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" , 2833__func__ ,t .second ,t .first .c_str ()); 2834attr = (llama_token_attr ) (attr |LLAMA_TOKEN_ATTR_CONTROL ); 2835 } 2836 } 2837 } 2838 } 2839 2840// auto-detect unused tokens: e.g. control tokens with the word "unused" 2841// ideally, these tokens should be marked as unused during conversion 2842 { 2843uint32_t n_unused = 0 ; 2844 2845for (const auto & t :token_to_id ) { 2846auto & attr = id_to_token [t .second ].attr ; 2847 2848if ((attr & LLAMA_TOKEN_ATTR_CONTROL )== 0 ) { 2849continue ; 2850 } 2851 2852if ((attr & LLAMA_TOKEN_ATTR_UNUSED )== 0 ) { 2853if (strstr (t .first .c_str (),"unused" )!= NULL ) { 2854attr = (llama_token_attr ) (attr |LLAMA_TOKEN_ATTR_UNUSED ); 2855 } 2856 } 2857 2858if (attr & LLAMA_TOKEN_ATTR_UNUSED ) { 2859n_unused ++ ; 2860 } 2861 } 2862 2863LLAMA_LOG_INFO ("%s: %u unused tokens\n" ,__func__ ,n_unused ); 2864 } 2865 2866// maintain a list of tokens that cause end-of-generation 2867// this is currently determined based on the token text, which is obviously not ideal 2868// ref: https://github.com/ggml-org/llama.cpp/issues/9606 2869special_eog_ids .clear (); 2870 2871if (special_fim_pad_id != LLAMA_TOKEN_NULL && special_eog_ids .count (special_fim_pad_id )== 0 ) { 2872special_eog_ids .insert (special_fim_pad_id ); 2873 } 2874 2875if (special_fim_rep_id != LLAMA_TOKEN_NULL && special_eog_ids .count (special_fim_rep_id )== 0 ) { 2876special_eog_ids .insert (special_fim_rep_id ); 2877 } 2878 2879if (special_fim_sep_id != LLAMA_TOKEN_NULL && special_eog_ids .count (special_fim_sep_id )== 0 ) { 2880special_eog_ids .insert (special_fim_sep_id ); 2881 } 2882 2883for (const auto & t :token_to_id ) { 2884auto & attr = id_to_token [t .second ].attr ; 2885 2886if (false 2887|| t .first == "<|eot_id|>" 2888|| t .first == "<|im_end|>" 2889|| t .first == "<|end|>" 2890|| t .first == "<|return|>" // o200k_harmony 2891|| t .first == "<|call|>" // o200k_harmony 2892|| t .first == "<|flush|>" // solar-open 2893|| t .first == "<|calls|>" // solar-open 2894|| t .first == "<end_of_turn>" 2895|| t .first == "<|endoftext|>" 2896|| t .first == "</s>" // paddleocr 2897|| t .first == "<|eom_id|>" 2898|| t .first == "<EOT>" 2899|| t .first == "_<EOT>" 2900|| t .first == "[EOT]" // Kimi-K2 2901|| t .first == "[EOS]" // Kimi-K2 2902|| t .first == "<|end_of_text|>" 2903|| t .first == "<end_of_utterance>" // smoldocling 2904|| t .first == "<eos>" // gemma4 2905|| t .first == "<turn|>" // gemma4 2906|| t .first == "<|tool_response>" // gemma4 2907|| t .first == "<|end▁of▁sentence|>" // deepseek-ocr 2908|| t .first == "[e~[" // minimax-m2/m3 2909 ) { 2910special_eog_ids .insert (t .second ); 2911if ((attr & LLAMA_TOKEN_ATTR_CONTROL )== 0 ) { 2912LLAMA_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" , 2913__func__ ,t .second ,t .first .c_str ()); 2914attr = (llama_token_attr ) (attr |LLAMA_TOKEN_ATTR_CONTROL ); 2915 } 2916 }else { 2917if (attr & LLAMA_TOKEN_ATTR_CONTROL && !(attr & LLAMA_TOKEN_ATTR_UNUSED )) { 2918// token is control, but not marked as EOG -> print a debug log 2919if (special_eog_ids .count (t .second )== 0 ) { 2920LLAMA_LOG_DEBUG ("%s: control token: %6d '%s' is not marked as EOG\n" , 2921__func__ ,t .second ,t .first .c_str ()); 2922 } 2923 } 2924 } 2925 } 2926 2927// @ngxson : quick hack for gpt-oss, always render these tokens 2928for (const auto & t :token_to_id ) { 2929auto & attr = id_to_token [t .second ].attr ; 2930 2931if (t .first == "<|channel|>" || t .first == "<|message|>" || t .first == "<|start|>" || t .first == "<|constrain|>" ) { 2932LLAMA_LOG_WARN ("%s: setting token '%s' (%d) attribute to USER_DEFINED (%u), old attributes: %u\n" , 2933__func__ ,t .first .c_str (),t .second ,LLAMA_TOKEN_ATTR_USER_DEFINED ,attr ); 2934 2935attr = LLAMA_TOKEN_ATTR_USER_DEFINED ; 2936 } 2937 } 2938 2939// sanity checks 2940if (special_eos_id != LLAMA_TOKEN_NULL && special_eog_ids .count (special_eos_id )== 0 ) { 2941special_eog_ids .insert (special_eos_id ); 2942LLAMA_LOG_WARN ("%s: special_eos_id is not in special_eog_ids - the tokenizer config may be incorrect\n" ,__func__ ); 2943 } 2944 2945if (special_eot_id != LLAMA_TOKEN_NULL && special_eog_ids .count (special_eot_id )== 0 ) { 2946special_eog_ids .insert (special_eot_id ); 2947LLAMA_LOG_WARN ("%s: special_eot_id is not in special_eog_ids - the tokenizer config may be incorrect\n" ,__func__ ); 2948 } 2949 2950if (special_eom_id != LLAMA_TOKEN_NULL && special_eog_ids .count (special_eom_id )== 0 ) { 2951special_eog_ids .insert (special_eom_id ); 2952LLAMA_LOG_WARN ("%s: special_eom_id is not in special_eog_ids - the tokenizer config may be incorrect\n" ,__func__ ); 2953 } 2954 2955// TODO: workaround for o200k_harmony and solar-open tokenizer: the "<|end|>" token should not be EOG 2956// we don't have a good way to detect this, so for now, if we have "<|return|>" and "<|call|>" tokens ("<|calls|>" and "<|flush|>" for solar-open), 2957// we remove the "<|end|>" token from the EOG list 2958 { 2959bool has_return = false; 2960bool has_call = false; 2961bool has_end = false; 2962bool has_flush = false; 2963 2964llama_token end_id = LLAMA_TOKEN_NULL ; 2965 2966LLAMA_LOG_INFO ("%s: printing all EOG tokens:\n" ,__func__ ); 2967for (auto tid :special_eog_ids ) { 2968if (tid < 0 || tid >= (llama_token )id_to_token .size ()) { 2969LLAMA_LOG_WARN ("%s: EOG token id %d is out of range (vocab size %zu), skipping\n" , 2970__func__ ,tid ,id_to_token .size ()); 2971continue ; 2972 } 2973auto & text = id_to_token [tid ].text ; 2974 2975LLAMA_LOG_INFO ("%s: - %d ('%s')\n" ,__func__ ,tid ,text .c_str ()); 2976 2977if (text == "<|return|>" ) { 2978has_return = true; 2979 }else if (text == "<|call|>" || text == "<|calls|>" ) { 2980has_call = true; 2981 }else if (text == "<|flush|>" ) { 2982has_flush = true; 2983 }else if (text == "<|end|>" ) { 2984has_end = true; 2985end_id = tid ; 2986 } 2987 } 2988 2989if ((has_return && has_call && has_end )|| (has_call && has_flush && has_end )) { 2990special_eog_ids .erase (end_id ); 2991 2992auto & attr = id_to_token [end_id ].attr ; 2993attr = LLAMA_TOKEN_ATTR_USER_DEFINED ; 2994 2995LLAMA_LOG_WARN ("%s: special_eog_ids contains both '<|return|>' and '<|call|>', or '<|calls|>' and '<|flush|>' tokens, removing '<|end|>' token from EOG list\n" ,__func__ ); 2996 } 2997 } 2998 2999// workaround for gemma4 and paddleocr: do not include </s> as an eog token 3000 { 3001bool has_tool_response = false; 3002bool has_s = false; 3003 3004llama_token s_id = LLAMA_TOKEN_NULL ; 3005 3006for (auto tid :special_eog_ids ) { 3007if (tid < 0 || tid >= (llama_token )id_to_token .size ()) { 3008continue ; 3009 } 3010const auto & text = id_to_token [tid ].text ; 3011if (text == "<|tool_response>" ) { 3012has_tool_response = true; 3013 }else if (text == "</s>" ) { 3014has_s = true; 3015s_id = tid ; 3016 } 3017 } 3018 3019if (has_tool_response && has_s ) { 3020special_eog_ids .erase (s_id ); 3021 3022auto & attr = id_to_token [s_id ].attr ; 3023attr = LLAMA_TOKEN_ATTR_NORMAL ; 3024 3025LLAMA_LOG_WARN ("%s: special_eog_ids contains '<|tool_response>', removing '</s>' token from EOG list\n" ,__func__ ); 3026 } 3027 } 3028 } 3029 3030// build special tokens cache 3031 { 3032for (llama_token id = 0 ;id < (llama_token )n_tokens ;++ id ) { 3033if (id_to_token [id ].attr & (LLAMA_TOKEN_ATTR_CONTROL |LLAMA_TOKEN_ATTR_USER_DEFINED |LLAMA_TOKEN_ATTR_UNKNOWN )) { 3034cache_special_tokens .push_back (id ); 3035 } 3036 } 3037 3038 std::sort (cache_special_tokens .begin (),cache_special_tokens .end (), 3039 [& ] (const llama_token a ,const llama_token b ) { 3040return id_to_token [a ].text .size ()> id_to_token [b ].text .size (); 3041 } 3042 ); 3043 3044LLAMA_LOG_INFO ("%s: special tokens cache size = %u\n" ,__func__ , (uint32_t )cache_special_tokens .size ()); 3045 } 3046 3047// build token to piece cache 3048 { 3049size_t size_cache = 0 ; 3050 3051 std::vector < std::string > cache (n_tokens ); 3052 3053for (uint32_t id = 0 ;id < n_tokens ;++ id ) { 3054cache [id ]= token_to_piece_for_cache (id , true); 3055 3056size_cache += cache [id ].size (); 3057 } 3058 3059 std::swap (cache_token_to_piece ,cache ); 3060 3061LLAMA_LOG_INFO ("%s: token to piece cache size = %.4f MB\n" ,__func__ ,size_cache /1024.0 /1024.0 ); 3062 } 3063 3064// Handle per token attributes 3065//NOTE: Each model customizes per token attributes. 3066//NOTE: Per token attributes are missing from the GGUF file. 3067//TODO: Extract attributes from GGUF file. 3068 { 3069auto _contains_any = [] (const std::string & str ,const std::vector < std::string_view > & substrs )-> bool { 3070for (const auto & substr :substrs ) { 3071if (str .find (substr )!= std::string::npos ) { 3072return true; 3073 } 3074 } 3075return false; 3076 }; 3077 3078auto _set_tokenid_attr = [& ] (const llama_token id ,llama_token_attr attr ,bool value ) { 3079uint32_t current = id_to_token .at (id ).attr ; 3080current = value ? (current |attr ) : (current & ~attr ); 3081id_to_token [id ].attr = (llama_token_attr )current ; 3082 }; 3083 3084auto _set_token_attr = [& ] (const std::string & token ,llama_token_attr attr ,bool value ) { 3085_set_tokenid_attr (token_to_id .at (token ),attr ,value ); 3086 }; 3087 3088 std::string model_name ; 3089 std::string tokenizer_pre ; 3090 std::string general_arch ; 3091 3092ml .get_key (LLM_KV_GENERAL_NAME ,model_name , false); 3093ml .get_key (LLM_KV_TOKENIZER_PRE ,tokenizer_pre , false); 3094ml .get_key (LLM_KV_GENERAL_ARCHITECTURE ,general_arch , false); 3095 3096// model name to lowercase 3097 std::transform (model_name .begin (),model_name .end (),model_name .begin (), 3098 [] (const std::string::value_type x ) { 3099return std::tolower (x ); 3100 } 3101 ); 3102 3103// set attributes by model/tokenizer/architecture name 3104if (false 3105|| _contains_any (tokenizer_pre , {"jina-v2-de" ,"jina-v2-es" ,"jina-v2-code" }) 3106|| _contains_any (general_arch , {"nomic-bert-moe" ,"jina-bert-v3" }) 3107 ) { 3108if (token_to_id .count ("<mask>" )== 0 ) { 3109LLAMA_LOG_WARN ("%s: Mask token is missing in vocab, please reconvert model!\n" ,__func__ ); 3110 }else { 3111_set_token_attr ("<mask>" ,LLAMA_TOKEN_ATTR_LSTRIP , true); 3112 } 3113 }else if (_contains_any (model_name , {"phi-3" ,"phi3" })) { 3114for (auto id :cache_special_tokens ) { 3115_set_tokenid_attr (id ,LLAMA_TOKEN_ATTR_RSTRIP , true); 3116 } 3117for (const auto * token : {"</s>" }) { 3118_set_token_attr (token ,LLAMA_TOKEN_ATTR_RSTRIP , true); 3119 } 3120for (const auto * token : {"<unk>" ,"<s>" ,"<|endoftext|>" }) { 3121_set_token_attr (token ,LLAMA_TOKEN_ATTR_RSTRIP , false); 3122 } 3123 }else if (_contains_any (model_name , {"modern-bert" })) { 3124if (token_to_id .count ("[MASK]" )== 0 ) { 3125LLAMA_LOG_WARN ("%s: Mask token missing in vocab!\n" ,__func__ ); 3126 } 3127else { 3128_set_token_attr ("[MASK]" ,LLAMA_TOKEN_ATTR_LSTRIP , true); 3129 } 3130 } 3131 } 3132} 3133 3134enum llama_vocab_type llama_vocab::impl::get_type ()const { 3135return type ; 3136} 3137 3138std::string llama_vocab::impl::type_name ()const { 3139switch (type ) { 3140case LLAMA_VOCAB_TYPE_NONE :return "no vocab" ; 3141case LLAMA_VOCAB_TYPE_SPM :return "SPM" ; 3142case LLAMA_VOCAB_TYPE_BPE :return "BPE" ; 3143case LLAMA_VOCAB_TYPE_WPM :return "WPM" ; 3144case LLAMA_VOCAB_TYPE_UGM :return "UGM" ; 3145case LLAMA_VOCAB_TYPE_RWKV :return "RWKV" ; 3146case LLAMA_VOCAB_TYPE_PLAMO2 :return "PLaMo2" ; 3147case LLAMA_VOCAB_TYPE_TEST :return "TEST" ; 3148default :return "unknown" ; 3149 } 3150} 3151 3152bool llama_vocab::impl::is_normal (llama_token id )const { 3153GGML_ASSERT (type != LLAMA_VOCAB_TYPE_NONE ); 3154return id_to_token [id ].attr & LLAMA_TOKEN_ATTR_NORMAL ; 3155} 3156 3157bool llama_vocab::impl::is_unknown (llama_token id )const { 3158GGML_ASSERT (type != LLAMA_VOCAB_TYPE_NONE ); 3159return id_to_token [id ].attr & LLAMA_TOKEN_ATTR_UNKNOWN ; 3160} 3161 3162bool llama_vocab::impl::is_control (llama_token id )const { 3163GGML_ASSERT (type != LLAMA_VOCAB_TYPE_NONE ); 3164return id_to_token [id ].attr & LLAMA_TOKEN_ATTR_CONTROL ; 3165} 3166 3167bool llama_vocab::impl::is_byte (llama_token id )const { 3168GGML_ASSERT (type != LLAMA_VOCAB_TYPE_NONE ); 3169return id_to_token [id ].attr & LLAMA_TOKEN_ATTR_BYTE ; 3170} 3171 3172bool llama_vocab::impl::is_user_defined (llama_token id )const { 3173GGML_ASSERT (type != LLAMA_VOCAB_TYPE_NONE ); 3174return id_to_token [id ].attr & LLAMA_TOKEN_ATTR_USER_DEFINED ; 3175} 3176 3177bool llama_vocab::impl::is_unused (llama_token id )const { 3178GGML_ASSERT (type != LLAMA_VOCAB_TYPE_NONE ); 3179return id_to_token [id ].attr & LLAMA_TOKEN_ATTR_UNUSED ; 3180} 3181 3182bool llama_vocab::impl::is_eog (llama_token id )const { 3183return id != LLAMA_TOKEN_NULL && special_eog_ids .count (id )> 0 ; 3184} 3185 3186uint8_t llama_vocab::impl::token_to_byte (llama_token id )const { 3187GGML_ASSERT (get_type ()!= LLAMA_VOCAB_TYPE_NONE ); 3188GGML_ASSERT (is_byte (id )); 3189const auto & token_data = id_to_token .at (id ); 3190switch (get_type ()) { 3191case LLAMA_VOCAB_TYPE_SPM : 3192case LLAMA_VOCAB_TYPE_UGM : { 3193auto buf = token_data .text .substr (3 ,2 ); 3194return strtol (buf .c_str (),NULL ,16 ); 3195 } 3196case LLAMA_VOCAB_TYPE_BPE : { 3197// Gemma4 uses BPE with SPM-style byte fallback tokens (<0xXX>) 3198auto buf = token_data .text .substr (3 ,2 ); 3199return strtol (buf .c_str (),NULL ,16 ); 3200 } 3201case LLAMA_VOCAB_TYPE_WPM : { 3202GGML_ABORT ("fatal error" ); 3203 } 3204default : 3205GGML_ABORT ("fatal error" ); 3206 } 3207} 3208 3209llama_token_attr llama_vocab::impl::token_get_attr (llama_token id )const { 3210GGML_ASSERT (type != LLAMA_VOCAB_TYPE_NONE ); 3211return id_to_token .at (id ).attr ; 3212} 3213 3214void llama_vocab::impl::init_tokenizer (enum llama_vocab_type type ) { 3215LLAMA_LOG_DEBUG ("%s: initializing tokenizer for type %d\n" ,__func__ ,type ); 3216 3217switch (type ) { 3218case LLAMA_VOCAB_TYPE_SPM : 3219tokenizer = std::make_unique < llm_tokenizer_spm > (vocab ); 3220break ; 3221case LLAMA_VOCAB_TYPE_BPE : 3222tokenizer = std::make_unique < llm_tokenizer_bpe > (vocab ); 3223break ; 3224case LLAMA_VOCAB_TYPE_WPM : 3225tokenizer = std::make_unique < llm_tokenizer_wpm > (vocab ); 3226break ; 3227case LLAMA_VOCAB_TYPE_UGM : 3228tokenizer = std::make_unique < llm_tokenizer_ugm > (vocab ,precompiled_charsmap ); 3229break ; 3230case LLAMA_VOCAB_TYPE_RWKV : 3231tokenizer = std::make_unique < llm_tokenizer_rwkv > (vocab ); 3232break ; 3233case LLAMA_VOCAB_TYPE_PLAMO2 : 3234tokenizer = std::make_unique < llm_tokenizer_plamo2 > (vocab ); 3235break ; 3236case LLAMA_VOCAB_TYPE_TEST : 3237tokenizer = std::make_unique < llm_tokenizer > (); 3238break ; 3239default : 3240GGML_ABORT ("unsupported vocab type" ); 3241 } 3242} 3243 3244// 3245// (de-) tokenize 3246// 3247 3248// #define PRETOKENIZERDEBUG 3249 3250void llama_vocab::impl::tokenizer_st_partition (std::forward_list < fragment_buffer_variant > & buffer ,bool parse_special )const { 3251// for each special token 3252for (const llama_token special_id :cache_special_tokens ) { 3253const auto & data = vocab .get_token_data (special_id ); 3254const auto & text = data .text ; 3255 3256if (!parse_special && (data .attr & (LLAMA_TOKEN_ATTR_CONTROL |LLAMA_TOKEN_ATTR_UNKNOWN ))) { 3257// Ignore control and unknown tokens when parse_special == false 3258continue ; 3259// User-defined tokens are still pre-tokenized before everything else 3260// ref: https://github.com/huggingface/tokenizers/blob/fdd26ba9a3f0c133427aab0423888cbde91362d7/tokenizers/src/tokenizer/mod.rs#L726 3261// This is mostly relevant for neox-style tokenizers (mpt, olmo, stablelm, etc.) 3262 } 3263 3264// for each text fragment 3265 std::forward_list < fragment_buffer_variant > ::iterator it = buffer .begin (); 3266while (it != buffer .end ()) { 3267auto & fragment = (* it ); 3268 3269// if a fragment is text ( not yet processed ) 3270if (fragment .type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT ) { 3271const auto & raw_text = fragment .raw_text ; 3272 3273auto raw_text_base_offset = fragment .offset ; 3274auto raw_text_base_length = fragment .length ; 3275 3276// loop over the text 3277while (true) { 3278// find the first occurrence of a given special token in this fragment 3279// passing offset argument only limit the "search area" but match coordinates 3280// are still relative to the source full raw_text 3281// string_view begins at pos 0 for the same reason 3282auto match = std::string_view (raw_text .data (),raw_text_base_offset + raw_text_base_length ).find (text ,raw_text_base_offset ); 3283 3284// no occurrences found, stop processing this fragment for a given special token 3285if (match == std::string::npos )break ; 3286 3287#ifdef PRETOKENIZERDEBUG 3288LLAMA_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 ()); 3289#endif 3290auto source = std::distance (buffer .begin (),it ); 3291 3292// if match is further than base offset 3293// then we have some text to the left of it 3294if (match > raw_text_base_offset ) { 3295// left 3296const int64_t left_reminder_offset = raw_text_base_offset + 0 ; 3297int64_t left_reminder_length = match - raw_text_base_offset ; 3298 3299if (data .attr & LLAMA_TOKEN_ATTR_LSTRIP ) { 3300while (left_reminder_length > 0 && isspace (raw_text [left_reminder_offset + left_reminder_length - 1 ])) { 3301left_reminder_length -- ; 3302 } 3303 } 3304 3305if (left_reminder_length > 0 ) { 3306buffer .emplace_after (it ,raw_text ,left_reminder_offset ,left_reminder_length ); 3307it ++ ; 3308 } 3309 3310#ifdef PRETOKENIZERDEBUG 3311LLAMA_LOG_WARN ("FL: (%ld %ld) '%s'\n" ,left_reminder_offset ,left_reminder_length ,raw_text -> substr (left_reminder_offset ,left_reminder_length ).c_str ()); 3312#endif 3313 } 3314 3315// special token 3316buffer .emplace_after (it ,special_id ); 3317it ++ ; 3318 3319// right 3320if (match + text .length ()< raw_text_base_offset + raw_text_base_length ) { 3321int64_t right_reminder_offset = match + text .length (); 3322int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset )+ text .length ()); 3323 3324if (data .attr & LLAMA_TOKEN_ATTR_RSTRIP ) { 3325while (right_reminder_length > 0 && isspace (raw_text [right_reminder_offset ])) { 3326right_reminder_offset ++ ; 3327right_reminder_length -- ; 3328 } 3329 } 3330 3331if (right_reminder_length > 0 ) { 3332buffer .emplace_after (it ,raw_text ,right_reminder_offset ,right_reminder_length ); 3333it ++ ; 3334 } 3335 3336#ifdef PRETOKENIZERDEBUG 3337LLAMA_LOG_WARN ("FR: (%ld %ld) '%s'\n" ,right_reminder_offset ,right_reminder_length ,raw_text -> substr (right_reminder_offset ,right_reminder_length ).c_str ()); 3338#endif 3339 3340if (source == 0 ) { 3341buffer .erase_after (buffer .before_begin ()); 3342 }else { 3343buffer .erase_after (std::next (buffer .begin (), (source - 1 ))); 3344 } 3345 3346// repeat for the right side 3347raw_text_base_offset = right_reminder_offset ; 3348raw_text_base_length = right_reminder_length ; 3349 3350#ifdef PRETOKENIZERDEBUG 3351LLAMA_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 ()); 3352#endif 3353 }else { 3354if (source == 0 ) { 3355buffer .erase_after (buffer .before_begin ()); 3356 }else { 3357buffer .erase_after (std::next (buffer .begin (), (source - 1 ))); 3358 } 3359break ; 3360 } 3361 } 3362 } 3363it ++ ; 3364 } 3365 } 3366} 3367 3368// NOTE: avoid ever using this except for building the token_to_piece caches 3369std::string llama_vocab::impl::token_to_piece_for_cache (llama_token token ,bool special )const { 3370 std::string piece ; 3371piece .resize (piece .capacity ());// using string internal cache 3372const int n_chars = vocab .token_to_piece (token ,& piece [0 ],piece .size (),0 ,special ); 3373if (n_chars < 0 ) { 3374piece .resize (- n_chars ); 3375int check = vocab .token_to_piece (token ,& piece [0 ],piece .size (),0 ,special ); 3376GGML_ASSERT (check == - n_chars ); 3377 } 3378else { 3379piece .resize (n_chars ); 3380 } 3381 3382return piece ; 3383} 3384 3385static void llama_escape_whitespace (std::string & text ) { 3386replace_all (text ," " ,"\xe2\x96\x81" ); 3387} 3388 3389static void llama_unescape_whitespace (std::string & word ) { 3390replace_all (word ,"\xe2\x96\x81" ," " ); 3391} 3392 3393static std::string llama_decode_text (const std::string & text ) { 3394 std::string decoded_text ; 3395 3396const auto cpts = unicode_cpts_from_utf8 (text ); 3397for (const auto cpt :cpts ) { 3398const auto utf8 = unicode_cpt_to_utf8 (cpt ); 3399try { 3400decoded_text += unicode_utf8_to_byte (utf8 ); 3401 }catch (const std::out_of_range & /*e*/ ) { 3402decoded_text += "[UNK_BYTE_0x" ; 3403for (const auto c :utf8 ) { 3404decoded_text += format ("%02x" , (uint8_t )c ); 3405 } 3406decoded_text += text + "]" ; 3407 } 3408 } 3409 3410return decoded_text ; 3411} 3412 3413std::vector < llama_token > llama_vocab::impl::tokenize ( 3414const std::string & raw_text , 3415bool add_special , 3416bool parse_special )const { 3417GGML_ASSERT (tokenizer && "Tokenizer not initialized. Call llama_vocab::init_tokenizer() first." ); 3418 3419 std::vector < llama_token > output ; 3420 std::forward_list < fragment_buffer_variant > fragment_buffer ; 3421 3422if (!raw_text .empty ()) { 3423fragment_buffer .emplace_front (raw_text ,0 ,raw_text .length ()); 3424tokenizer_st_partition (fragment_buffer ,parse_special ); 3425 } 3426 3427switch (get_type ()) { 3428case LLAMA_VOCAB_TYPE_SPM : 3429 { 3430// OG tokenizer behavior: 3431// 3432// tokenizer.encode('', add_special_tokens=True) returns [1] 3433// tokenizer.encode('', add_special_tokens=False) returns [] 3434 3435bool is_prev_special = true;// prefix with space if first token 3436 3437if (add_special && add_bos ) { 3438GGML_ASSERT (special_bos_id != LLAMA_TOKEN_NULL ); 3439output .push_back (special_bos_id ); 3440is_prev_special = true; 3441 } 3442 3443for (const auto & fragment :fragment_buffer ) { 3444if (fragment .type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT ) { 3445 std::string text ; 3446 3447// prefix with space if previous is special 3448if (add_space_prefix && is_prev_special ) { 3449text = ' ' ; 3450 } 3451 3452text += fragment .raw_text .substr (fragment .offset ,fragment .length ); 3453 3454#ifdef PRETOKENIZERDEBUG 3455LLAMA_LOG_WARN ("TT: (%ld %ld %ld) '%s'\n" ,text .length (),fragment .offset ,fragment .length ,text .c_str ()); 3456#endif 3457llama_escape_whitespace (text ); 3458llm_tokenizer_spm_session session (vocab ); 3459session .tokenize (text ,output ); 3460is_prev_special = false; 3461 }else {// if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN) 3462output .push_back (fragment .token ); 3463is_prev_special = true; 3464 } 3465 } 3466 3467if (add_special && add_bos && output .size () >=2 && output [1 ]== special_bos_id ) { 3468LLAMA_LOG_WARN ( 3469"%s: Added a BOS token to the prompt as specified by the model but the prompt " 3470"also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. " 3471"Are you sure this is what you want?\n" ,__FUNCTION__ ); 3472 } 3473 3474if (add_special && add_eos ) { 3475GGML_ASSERT (special_eos_id != LLAMA_TOKEN_NULL ); 3476output .push_back (special_eos_id ); 3477 } 3478 }break ; 3479case LLAMA_VOCAB_TYPE_BPE : 3480 { 3481// it calls some other methods that are not exist in llm_tokenizer, 3482// here just cast it to bpe tokenizer object 3483const llm_tokenizer_bpe * tok_bpe = static_cast < const llm_tokenizer_bpe *> (tokenizer .get ()); 3484 3485 std::unique_ptr < llm_tokenizer_bpe_session > session ; 3486if (vocab .get_tokenizer_model ()== "hybriddna" ) { 3487session = std::make_unique < llm_tokenizer_hybriddna_session > (vocab ,* tok_bpe ); 3488 }else if (vocab .get_tokenizer_model ()== "whitespace" ) { 3489session = std::make_unique < llm_tokenizer_whitespace_session > (vocab ,* tok_bpe ); 3490 }else { 3491session = std::make_unique < llm_tokenizer_bpe_session > (vocab ,* tok_bpe ); 3492 } 3493 3494if (add_special ) { 3495session -> append_bos (output ); 3496 } 3497for (const auto & fragment :fragment_buffer ) { 3498if (fragment .type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT ) { 3499 std::string text = fragment .raw_text .substr (fragment .offset ,fragment .length ); 3500 3501if (escape_whitespaces ) { 3502llama_escape_whitespace (text ); 3503 } 3504 3505#ifdef PRETOKENIZERDEBUG 3506LLAMA_LOG_WARN ("TT: (%ld %ld %ld) '%s'\n" ,text .length (),fragment .offset ,fragment .length ,text .c_str ()); 3507#endif 3508session -> tokenize (text ,output ); 3509 }else {// if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN) 3510session -> append (fragment .token ,output ); 3511 } 3512 } 3513 3514if (add_special ) { 3515session -> append_eos (output ); 3516session -> check_double_bos_eos (output ); 3517 } 3518 }break ; 3519case LLAMA_VOCAB_TYPE_WPM : 3520 { 3521if (add_special ) { 3522GGML_ASSERT (special_bos_id != LLAMA_TOKEN_NULL ); 3523output .push_back (special_bos_id ); 3524 } 3525 3526llm_tokenizer_wpm_session session (vocab ); 3527 3528for (const auto & fragment :fragment_buffer ) { 3529if (fragment .type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT ) { 3530 std::string text = fragment .raw_text .substr (fragment .offset ,fragment .length ); 3531 3532#ifdef PRETOKENIZERDEBUG 3533LLAMA_LOG_WARN ("TT: (%ld %ld %ld) '%s'\n" ,text .length (),fragment .offset ,fragment .length ,text .c_str ()); 3534#endif 3535session .tokenize (text ,output ); 3536 }else {// if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN) 3537output .push_back (fragment .token ); 3538 } 3539 } 3540 3541if (add_special ) { 3542GGML_ASSERT (special_sep_id != LLAMA_TOKEN_NULL ); 3543output .push_back (special_sep_id ); 3544 } 3545 }break ; 3546case LLAMA_VOCAB_TYPE_UGM : 3547 { 3548if (add_special && add_bos ) { 3549GGML_ASSERT (special_bos_id != LLAMA_TOKEN_NULL ); 3550output .push_back (special_bos_id ); 3551 } 3552llm_tokenizer_ugm_session session (vocab ,* static_cast < const llm_tokenizer_ugm *> (tokenizer .get ())); 3553 3554for (const auto & fragment :fragment_buffer ) { 3555if (fragment .type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT ) { 3556 std::string text = fragment .raw_text .substr (fragment .offset ,fragment .length ); 3557#ifdef PRETOKENIZERDEBUG 3558LLAMA_LOG_WARN ("TT: (%ld %ld %ld) '%s'\n" ,text .length (),fragment .offset ,fragment .length ,text .c_str ()); 3559#endif 3560session .tokenize (text ,output ); 3561 }else {// if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN) 3562output .push_back (fragment .token ); 3563 } 3564 } 3565 3566if (add_special && add_bos && output .size () >=2 && output [1 ]== special_bos_id ) { 3567LLAMA_LOG_WARN ( 3568"%s: Added a BOS token to the prompt as specified by the model but the prompt " 3569"also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. " 3570"Are you sure this is what you want?\n" ,__FUNCTION__ ); 3571 } 3572 3573if (add_special && add_eos ) { 3574GGML_ASSERT (special_eos_id != LLAMA_TOKEN_NULL ); 3575output .push_back (special_eos_id ); 3576 } 3577 }break ; 3578case LLAMA_VOCAB_TYPE_RWKV : 3579 { 3580llm_tokenizer_rwkv_session session (vocab ,* static_cast < const llm_tokenizer_rwkv *> (tokenizer .get ())); 3581for (const auto & fragment :fragment_buffer ) { 3582if (fragment .type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT ) { 3583 std::string text = fragment .raw_text .substr (fragment .offset ,fragment .length ); 3584 3585#ifdef PRETOKENIZERDEBUG 3586LLAMA_LOG_WARN ("TT: (%ld %ld %ld) '%s'\n" ,text .length (),fragment .offset ,fragment .length ,text .c_str ()); 3587#endif 3588 3589session .tokenize (text ,output ); 3590 }else {// if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN) 3591output .push_back (fragment .token ); 3592 } 3593 } 3594 }break ; 3595case LLAMA_VOCAB_TYPE_PLAMO2 : 3596 { 3597llm_tokenizer_plamo2_session session (* static_cast < const llm_tokenizer_plamo2 *> (tokenizer .get ())); 3598for (const auto & fragment :fragment_buffer ) { 3599if (fragment .type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT ) { 3600 std::string text = fragment .raw_text .substr (fragment .offset ,fragment .length ); 3601 3602#ifdef PRETOKENIZERDEBUG 3603LLAMA_LOG_WARN ("TT: (%ld %ld %ld) '%s'\n" ,text .length (),fragment .offset ,fragment .length ,text .c_str ()); 3604#endif 3605 3606session .tokenize (text ,output ); 3607 }else {// if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN) 3608output .push_back (fragment .token ); 3609 } 3610 } 3611 }break ; 3612case LLAMA_VOCAB_TYPE_TEST : 3613 { 3614const uint32_t n_vocab = vocab .n_tokens (); 3615constexpr size_t chunk_size = 5 ; 3616 3617// reserve output to avoid repeated reallocations 3618size_t n_tokens = 0 ; 3619for (const auto & fragment :fragment_buffer ) { 3620if (fragment .type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT ) { 3621n_tokens += (fragment .length + chunk_size - 1 ) /chunk_size ; 3622 }else { 3623++ n_tokens ; 3624 } 3625 } 3626output .reserve (output .size ()+ n_tokens ); 3627 3628for (const auto & fragment :fragment_buffer ) { 3629if (fragment .type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT ) { 3630const auto & text = fragment .raw_text ; 3631const size_t begin = fragment .offset ; 3632const size_t end = begin + fragment .length ; 3633size_t pos = begin ; 3634while (pos < end ) { 3635const size_t n = std::min (chunk_size ,end - pos ); 3636uint64_t hash = 0 ; 3637for (size_t i = 0 ;i < n ;++ i ) { 3638hash = hash * 31 + (uint8_t )text [pos + i ]; 3639 } 3640output .push_back ((llama_token )(hash %n_vocab )); 3641pos += n ; 3642 } 3643 }else {// if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN) 3644output .push_back (fragment .token ); 3645 } 3646 } 3647 }break ; 3648case LLAMA_VOCAB_TYPE_NONE : 3649GGML_ABORT ("fatal error" ); 3650 } 3651 3652return output ; 3653} 3654 3655int32_t llama_vocab::impl::token_to_piece (llama_token token ,char * buf ,int32_t length ,int32_t lstrip ,bool special )const { 3656// ref: https://github.com/ggml-org/llama.cpp/pull/7587#discussion_r1620983843 3657static const int attr_special = LLAMA_TOKEN_ATTR_UNKNOWN |LLAMA_TOKEN_ATTR_CONTROL ; 3658const llama_token_attr attr = token_get_attr (token ); 3659if (!special && (attr & attr_special )) { 3660return 0 ; 3661 } 3662 3663// copy piece chars to output text buffer 3664// skip up to 'lstrip' leading spaces before copying 3665auto _try_copy = [= ] (const char * token ,size_t size )-> int32_t { 3666if (size >=static_cast < size_t > (std::numeric_limits < int32_t > ::max ())) { 3667GGML_ABORT ("invalid token size: %zu exceeds int32_t limit" ,size ); 3668 } 3669 3670for (int32_t i = 0 ;i < lstrip && size && * token == ' ' ;++ i ) { 3671token ++ ; 3672size -- ; 3673 } 3674if (length < (int32_t )size ) { 3675return - (int32_t )size ; 3676 } 3677memcpy (buf ,token ,size ); 3678return (int32_t )size ; 3679 }; 3680 3681// if we have a cache - use it 3682 { 3683const auto & cache = cache_token_to_piece ; 3684 3685if (!cache .empty ()) { 3686const auto & result = cache .at (token ); 3687return _try_copy (result .data (),result .size ()); 3688 } 3689 } 3690 3691if (0 <=token && token < (int32_t )id_to_token .size ()) { 3692const std::string & token_text = id_to_token [token ].text ; 3693switch (get_type ()) { 3694case LLAMA_VOCAB_TYPE_WPM : 3695case LLAMA_VOCAB_TYPE_SPM : 3696case LLAMA_VOCAB_TYPE_UGM : { 3697// NOTE: we accept all unsupported token types, 3698// suppressing them like CONTROL tokens. 3699if (attr & (attr_special |LLAMA_TOKEN_ATTR_USER_DEFINED )) { 3700return _try_copy (token_text .data (),token_text .size ()); 3701 } 3702if (attr & LLAMA_TOKEN_ATTR_NORMAL ) { 3703 std::string result = token_text ; 3704llama_unescape_whitespace (result ); 3705return _try_copy (result .data (),result .size ()); 3706 } 3707if (attr & LLAMA_TOKEN_ATTR_BYTE ) { 3708char byte = (char )token_to_byte (token ); 3709return _try_copy ((char * )& byte ,1 ); 3710 } 3711break ; 3712 } 3713case LLAMA_VOCAB_TYPE_BPE : { 3714// NOTE: we accept all unsupported token types, 3715// suppressing them like CONTROL tokens. 3716if (attr & (attr_special |LLAMA_TOKEN_ATTR_USER_DEFINED )) { 3717return _try_copy (token_text .data (),token_text .size ()); 3718 } 3719if (attr & LLAMA_TOKEN_ATTR_NORMAL ) { 3720if (escape_whitespaces ) { 3721// SPM-style BPE: tokens contain ▁ for spaces 3722 std::string result = token_text ; 3723llama_unescape_whitespace (result ); 3724return _try_copy (result .data (),result .size ()); 3725 } 3726 std::string result = llama_decode_text (token_text ); 3727return _try_copy (result .data (),result .size ()); 3728 } 3729if (attr & LLAMA_TOKEN_ATTR_BYTE ) { 3730char byte = (char )token_to_byte (token ); 3731return _try_copy ((char * )& byte ,1 ); 3732 } 3733break ; 3734 } 3735case LLAMA_VOCAB_TYPE_RWKV : { 3736 std::vector < uint8_t > result = llama_unescape_rwkv_token (token_text ); 3737 3738// If we don't have enough space, return an error 3739if (result .size ()> (size_t )length ) { 3740return - (int )result .size (); 3741 } 3742 3743memcpy (buf ,result .data (),result .size ()); 3744return (int )result .size (); 3745 } 3746case LLAMA_VOCAB_TYPE_TEST : { 3747// tokens -> text: simply stringify the token id in hex 3748 std::string result = format ("%x" ,token ); 3749return _try_copy (result .data (),result .size ()); 3750 } 3751case LLAMA_VOCAB_TYPE_PLAMO2 : { 3752// PLaMo-2 uses similar token handling as BPE/SPM 3753if (vocab .is_byte (token )) { 3754// Handle byte tokens like <0xXX> 3755if (token_text .length ()== 6 && token_text .substr (0 ,3 )== "<0x" && token_text .back ()== '>' ) { 3756 std::string hex_str = token_text .substr (3 ,2 ); 3757if (std::isxdigit (static_cast < unsigned char > (hex_str [0 ]))&& std::isxdigit (static_cast < unsigned char > (hex_str [1 ]))) { 3758int hex_val = std::stoi (hex_str ,nullptr ,16 ); 3759if (length < 1 ) { 3760return -1 ; 3761 } 3762buf [0 ]= static_cast < char > (hex_val ); 3763return 1 ; 3764 } 3765 } 3766 } 3767 3768// Normal token - just copy the text 3769 std::string result = token_text ; 3770return _try_copy (result .data (),result .size ()); 3771 } 3772default : 3773GGML_ABORT ("fatal error" ); 3774 } 3775 } 3776 3777return 0 ; 3778} 3779 3780const std::string & llama_vocab::impl::token_to_piece (llama_token token )const { 3781return cache_token_to_piece .at (token ); 3782} 3783 3784int32_t llama_vocab::impl::detokenize ( 3785const llama_token * tokens , 3786int32_t n_tokens , 3787char * text , 3788int32_t text_len_max , 3789bool remove_special , 3790bool unparse_special )const { 3791if (type == LLAMA_VOCAB_TYPE_NONE ) { 3792return 0 ; 3793 } 3794 3795GGML_ASSERT (tokenizer && "Tokenizer not initialized. Call llama_vocab::init_tokenizer() first." ); 3796 3797int32_t avail = text_len_max ; 3798int32_t total = 0 ; 3799 3800// remove the leading space 3801bool remove_space = add_space_prefix ; 3802 3803if (remove_special && add_bos ) { 3804if (n_tokens > 0 && tokens [0 ]== special_bos_id ) { 3805remove_space = false; 3806n_tokens -- ; 3807tokens ++ ; 3808 } 3809 } 3810 3811if (remove_special && add_eos ) { 3812if (n_tokens > 0 && tokens [n_tokens - 1 ]== special_eos_id ) { 3813n_tokens -- ; 3814 } 3815 } 3816 3817for (int32_t i = 0 ;i < n_tokens ;++ i ) { 3818GGML_ASSERT (avail >=0 ); 3819int32_t n_chars = token_to_piece (tokens [i ],text ,avail ,remove_space ,unparse_special ); 3820remove_space = false; 3821if (n_chars < 0 ) { 3822avail = 0 ; 3823total -= n_chars ; 3824 }else if (n_chars > 0 ) { 3825avail -= n_chars ; 3826text += n_chars ; 3827total += n_chars ; 3828 } 3829 } 3830 3831if (total > text_len_max ) { 3832return - total ; 3833 } 3834 3835if (clean_spaces ) { 3836text -= total ;// restart text 3837 3838// first pass: characters ?!., //TODO: where do these characters come from? 3839const int32_t total1 = total ; 3840total = total ?1 :0 ; 3841for (int32_t i = 1 ;i < total1 ;++ i ) { 3842const char x = text [i ]; 3843if (text [i - 1 ]== ' ' ) { 3844if (x == '?' || x == '!' || x == '.' || x == ',' ) {// " ?", " !", " .", " ," 3845total -- ;// remove space 3846 } 3847 } 3848text [total ++ ]= x ; 3849 } 3850 3851// second pass: strip single apostrophe between spaces 3852const int32_t total2 = total ; 3853total = total ?1 :0 ; 3854for (int32_t i = 1 ;i < total2 ;++ i ) { 3855const char x = text [i ]; 3856if (x == '\'' && i + 1 < total2 && text [i - 1 ]== ' ' && text [i + 1 ]== ' ' ) {// " ' " 3857total -- ;// remove prev space 3858text [++ i ]= '\0' ;// remove next space 3859 } 3860text [total ++ ]= x ; 3861 } 3862 3863// third pass: apostrophe contractions //NOTE: this makes sense? 3864const int32_t total3 = total ; 3865total = total ?1 :0 ; 3866for (int32_t i = 1 ;i < total3 ;++ i ) { 3867const char x = text [i ]; 3868if (text [i - 1 ]== ' ' ) { 3869if (x == '\'' && i + 1 < total3 ) { 3870const char x1 = text [i + 1 ]; 3871if (x1 == 't' || x1 == 'd' ) {// " 't", " 'd" 3872//total--; // remove space 3873 }else if (x1 == 's' || x1 == 'm' ) {// " 's", " 'm" 3874total -- ;// remove space 3875 }else if (i + 2 < total3 ) { 3876const char x2 = text [i + 2 ]; 3877if ((x1 == 'l' && x2 == 'l' )) {// " 'll" 3878//total--; // remove space 3879 }else if ((x1 == 'r' && x2 == 'e' )|| (x1 == 'v' && x2 == 'e' )) {// " 're", " 've" 3880total -- ;// remove space 3881 }else { 3882//total--; // remove space 3883 } 3884 }else { 3885//total--; // remove space 3886 } 3887 } 3888 } 3889text [total ++ ]= x ; 3890 } 3891 } 3892 3893return total <=text_len_max ?total :- total ; 3894} 3895 3896void llama_vocab::impl::print_info ()const { 3897LLAMA_LOG_INFO ("%s: vocab type = %s\n" ,__func__ ,type_name ().c_str ()); 3898LLAMA_LOG_INFO ("%s: n_vocab = %u\n" ,__func__ ,vocab .n_tokens ()); 3899LLAMA_LOG_INFO ("%s: n_merges = %u\n" ,__func__ , (uint32_t )bpe_ranks .size ()); 3900 3901// special tokens 3902if (special_bos_id != LLAMA_TOKEN_NULL ) {LLAMA_LOG_INFO ("%s: BOS token = %d '%s'\n" ,__func__ ,special_bos_id ,id_to_token .at (special_bos_id ).text .c_str () ); } 3903if (special_eos_id != LLAMA_TOKEN_NULL ) {LLAMA_LOG_INFO ("%s: EOS token = %d '%s'\n" ,__func__ ,special_eos_id ,id_to_token .at (special_eos_id ).text .c_str () ); } 3904if (special_eot_id != LLAMA_TOKEN_NULL ) {LLAMA_LOG_INFO ("%s: EOT token = %d '%s'\n" ,__func__ ,special_eot_id ,id_to_token .at (special_eot_id ).text .c_str () ); } 3905if (special_eom_id != LLAMA_TOKEN_NULL ) {LLAMA_LOG_INFO ("%s: EOM token = %d '%s'\n" ,__func__ ,special_eom_id ,id_to_token .at (special_eom_id ).text .c_str () ); } 3906if (special_unk_id != LLAMA_TOKEN_NULL ) {LLAMA_LOG_INFO ("%s: UNK token = %d '%s'\n" ,__func__ ,special_unk_id ,id_to_token .at (special_unk_id ).text .c_str () ); } 3907if (special_sep_id != LLAMA_TOKEN_NULL ) {LLAMA_LOG_INFO ("%s: SEP token = %d '%s'\n" ,__func__ ,special_sep_id ,id_to_token .at (special_sep_id ).text .c_str () ); } 3908if (special_pad_id != LLAMA_TOKEN_NULL ) {LLAMA_LOG_INFO ("%s: PAD token = %d '%s'\n" ,__func__ ,special_pad_id ,id_to_token .at (special_pad_id ).text .c_str () ); } 3909if (special_mask_id != LLAMA_TOKEN_NULL ) {LLAMA_LOG_INFO ("%s: MASK token = %d '%s'\n" ,__func__ ,special_mask_id ,id_to_token .at (special_mask_id ).text .c_str () ); } 3910 3911if (linefeed_id != LLAMA_TOKEN_NULL ) {LLAMA_LOG_INFO ("%s: LF token = %d '%s'\n" ,__func__ ,linefeed_id ,id_to_token .at (linefeed_id ).text .c_str () ); } 3912 3913if (special_fim_pre_id != LLAMA_TOKEN_NULL ) {LLAMA_LOG_INFO ("%s: FIM PRE token = %d '%s'\n" ,__func__ ,special_fim_pre_id ,id_to_token .at (special_fim_pre_id ).text .c_str () ); } 3914if (special_fim_suf_id != LLAMA_TOKEN_NULL ) {LLAMA_LOG_INFO ("%s: FIM SUF token = %d '%s'\n" ,__func__ ,special_fim_suf_id ,id_to_token .at (special_fim_suf_id ).text .c_str () ); } 3915if (special_fim_mid_id != LLAMA_TOKEN_NULL ) {LLAMA_LOG_INFO ("%s: FIM MID token = %d '%s'\n" ,__func__ ,special_fim_mid_id ,id_to_token .at (special_fim_mid_id ).text .c_str () ); } 3916if (special_fim_pad_id != LLAMA_TOKEN_NULL ) {LLAMA_LOG_INFO ("%s: FIM PAD token = %d '%s'\n" ,__func__ ,special_fim_pad_id ,id_to_token .at (special_fim_pad_id ).text .c_str () ); } 3917if (special_fim_rep_id != LLAMA_TOKEN_NULL ) {LLAMA_LOG_INFO ("%s: FIM REP token = %d '%s'\n" ,__func__ ,special_fim_rep_id ,id_to_token .at (special_fim_rep_id ).text .c_str () ); } 3918if (special_fim_sep_id != LLAMA_TOKEN_NULL ) {LLAMA_LOG_INFO ("%s: FIM SEP token = %d '%s'\n" ,__func__ ,special_fim_sep_id ,id_to_token .at (special_fim_sep_id ).text .c_str () ); } 3919 3920for (const auto & id :special_eog_ids ) { 3921LLAMA_LOG_INFO ("%s: EOG token = %d '%s'\n" ,__func__ ,id ,id_to_token .at (id ).text .c_str () ); 3922 } 3923 3924LLAMA_LOG_INFO ("%s: max token length = %d\n" ,__func__ ,max_token_len ); 3925} 3926 3927llama_vocab::llama_vocab () :pimpl (new impl (* this )) { 3928} 3929 3930llama_vocab::~llama_vocab ()= default ; 3931 3932void llama_vocab::load (llama_model_loader & ml ,const LLM_KV & kv ) { 3933pimpl -> load (ml ,kv ); 3934} 3935 3936std::string llama_vocab::get_tokenizer_model ()const { 3937return pimpl -> tokenizer_model ; 3938} 3939 3940std::string llama_vocab::get_tokenizer_pre ()const { 3941return pimpl -> tokenizer_pre ; 3942} 3943 3944enum llama_vocab_type llama_vocab::get_type ()const { 3945return pimpl -> type ; 3946} 3947 3948enum llama_vocab_pre_type llama_vocab::get_pre_type ()const { 3949return pimpl -> pre_type ; 3950} 3951 3952uint32_t llama_vocab::n_tokens ()const { 3953return (uint32_t )pimpl -> id_to_token .size (); 3954} 3955 3956uint32_t llama_vocab::n_token_types ()const { 3957return (uint32_t )pimpl -> n_token_types ; 3958} 3959 3960std::string llama_vocab::type_name ()const { 3961return pimpl -> type_name (); 3962} 3963 3964bool llama_vocab::is_normal (llama_token id )const { 3965return pimpl -> is_normal (id ); 3966} 3967 3968bool llama_vocab::is_unknown (llama_token id )const { 3969return pimpl -> is_unknown (id ); 3970} 3971 3972bool llama_vocab::is_control (llama_token id )const { 3973return pimpl -> is_control (id ); 3974} 3975 3976bool llama_vocab::is_byte (llama_token id )const { 3977return pimpl -> is_byte (id ); 3978} 3979 3980bool llama_vocab::is_user_defined (llama_token id )const { 3981return pimpl -> is_user_defined (id ); 3982} 3983 3984bool llama_vocab::is_unused (llama_token id )const { 3985return pimpl -> is_unused (id ); 3986} 3987 3988bool llama_vocab::is_eog (llama_token id )const { 3989return pimpl -> is_eog (id ); 3990} 3991 3992uint8_t llama_vocab::token_to_byte (llama_token id )const { 3993return pimpl -> token_to_byte (id ); 3994} 3995 3996llama_token llama_vocab::byte_to_token (uint8_t ch )const { 3997GGML_ASSERT (get_type ()!= LLAMA_VOCAB_TYPE_NONE ); 3998static const char * hex = "0123456789ABCDEF" ; 3999switch (get_type ()) { 4000case LLAMA_VOCAB_TYPE_SPM : 4001case LLAMA_VOCAB_TYPE_UGM : { 4002const char buf [7 ]= {'<' ,'0' ,'x' ,hex [ch >>4 ],hex [ch & 15 ],'>' ,0 }; 4003auto token = pimpl -> token_to_id .find (buf ); 4004if (token != pimpl -> token_to_id .end ()) { 4005return (* token ).second ; 4006 } 4007// Try to fall back to just the byte as a string 4008const char buf2 [2 ]= { (char )ch ,0 }; 4009return pimpl -> token_to_id .at (buf2 ); 4010 } 4011case LLAMA_VOCAB_TYPE_WPM : 4012case LLAMA_VOCAB_TYPE_BPE : { 4013return pimpl -> token_to_id .at (unicode_byte_to_utf8 (ch )); 4014 } 4015case LLAMA_VOCAB_TYPE_PLAMO2 : { 4016// PLaMo-2 uses byte tokens in format <0xXX> 4017char hex_str [8 ]; 4018snprintf (hex_str ,sizeof (hex_str ),"<0x%02X>" ,ch ); 4019return pimpl -> token_to_id .at (hex_str ); 4020 } 4021case LLAMA_VOCAB_TYPE_TEST : 4022// TEST tokens have no byte-level mapping 4023return LLAMA_TOKEN_NULL ; 4024default : 4025GGML_ABORT ("fatal error" ); 4026 } 4027} 4028 4029llama_token llama_vocab::text_to_token (const std::string & text )const { 4030GGML_ASSERT (pimpl -> type != LLAMA_VOCAB_TYPE_NONE ); 4031auto it = pimpl -> token_to_id .find (text ); 4032if (it != pimpl -> token_to_id .end ()) { 4033return (* it ).second ; 4034 } 4035return LLAMA_TOKEN_NULL ; 4036} 4037 4038const llama_vocab::token_data & llama_vocab::get_token_data (llama_token id )const { 4039GGML_ASSERT (pimpl -> type != LLAMA_VOCAB_TYPE_NONE ); 4040return pimpl -> id_to_token .at (id ); 4041} 4042 4043const char * llama_vocab::token_get_text (llama_token id )const { 4044GGML_ASSERT (pimpl -> type != LLAMA_VOCAB_TYPE_NONE ); 4045return pimpl -> id_to_token .at (id ).text .c_str (); 4046} 4047 4048float llama_vocab::token_get_score (llama_token id )const { 4049GGML_ASSERT (pimpl -> type != LLAMA_VOCAB_TYPE_NONE ); 4050return pimpl -> id_to_token .at (id ).score ; 4051} 4052 4053llama_token_attr llama_vocab::token_get_attr (llama_token id )const { 4054return pimpl -> token_get_attr (id ); 4055} 4056 4057llama_token llama_vocab::token_bos ()const { 4058return pimpl -> special_bos_id ; 4059} 4060 4061llama_token llama_vocab::token_eos ()const { 4062return pimpl -> special_eos_id ; 4063} 4064 4065llama_token llama_vocab::token_eot ()const { 4066return pimpl -> special_eot_id ; 4067} 4068 4069llama_token llama_vocab::token_eom ()const { 4070return pimpl -> special_eom_id ; 4071} 4072 4073llama_token llama_vocab::token_unk ()const { 4074return pimpl -> special_unk_id ; 4075} 4076 4077llama_token llama_vocab::token_sep ()const { 4078return pimpl -> special_sep_id ; 4079} 4080 4081llama_token llama_vocab::token_nl ()const { 4082return pimpl -> linefeed_id ; 4083} 4084 4085llama_token llama_vocab::token_pad ()const { 4086return pimpl -> special_pad_id ; 4087} 4088 4089llama_token llama_vocab::token_prefix ()const { 4090return pimpl -> special_fim_pre_id ; 4091} 4092 4093llama_token llama_vocab::token_middle ()const { 4094return pimpl -> special_fim_mid_id ; 4095} 4096 4097llama_token llama_vocab::token_suffix ()const { 4098return pimpl -> special_fim_suf_id ; 4099} 4100 4101llama_token llama_vocab::token_fim_pre ()const { 4102return pimpl -> special_fim_pre_id ; 4103} 4104 4105llama_token llama_vocab::token_fim_suf ()const { 4106return pimpl -> special_fim_suf_id ; 4107} 4108 4109llama_token llama_vocab::token_fim_mid ()const { 4110return pimpl -> special_fim_mid_id ; 4111} 4112 4113llama_token llama_vocab::token_fim_pad ()const { 4114return pimpl -> special_fim_pad_id ; 4115} 4116 4117llama_token llama_vocab::token_fim_rep ()const { 4118return pimpl -> special_fim_rep_id ; 4119} 4120 4121llama_token llama_vocab::token_fim_sep ()const { 4122return pimpl -> special_fim_sep_id ; 4123} 4124 4125llama_token llama_vocab::token_mask ()const { 4126return pimpl -> special_mask_id ; 4127} 4128 4129bool llama_vocab::get_add_space_prefix ()const { 4130return pimpl -> add_space_prefix ; 4131} 4132 4133bool llama_vocab::get_add_bos ()const { 4134return pimpl -> add_bos ; 4135} 4136 4137bool llama_vocab::get_add_eos ()const { 4138return pimpl -> add_eos ; 4139} 4140 4141bool llama_vocab::get_add_sep ()const { 4142return pimpl -> add_sep ; 4143} 4144 4145bool llama_vocab::get_ignore_merges ()const { 4146return pimpl -> ignore_merges ; 4147} 4148 4149bool llama_vocab::get_clean_spaces ()const { 4150return pimpl -> clean_spaces ; 4151} 4152 4153bool llama_vocab::get_remove_extra_whitespaces ()const { 4154return pimpl -> remove_extra_whitespaces ; 4155} 4156 4157bool llama_vocab::get_escape_whitespaces ()const { 4158return pimpl -> escape_whitespaces ; 4159} 4160 4161bool llama_vocab::get_treat_whitespace_as_suffix ()const { 4162return pimpl -> treat_whitespace_as_suffix ; 4163} 4164 4165const llama_vocab::normalizer_options & llama_vocab::get_normalizer_opts ()const { 4166return pimpl -> normalizer_opts ; 4167} 4168 4169const std::vector < llama_token > & llama_vocab::get_suppress_tokens ()const { 4170return pimpl -> suppress_tokens ; 4171} 4172 4173int llama_vocab::max_token_len ()const { 4174return pimpl -> max_token_len ; 4175} 4176 4177int llama_vocab::find_bpe_rank (const std::string & token_left ,const std::string & token_right )const { 4178GGML_ASSERT (token_left .find (' ' )== std::string::npos ); 4179GGML_ASSERT (token_right .find (' ' )== std::string::npos ); 4180 4181auto it = pimpl -> bpe_ranks .find (std::make_pair (token_left ,token_right )); 4182if (it == pimpl -> bpe_ranks .end ()) { 4183return -1 ; 4184 } 4185 4186return it -> second ; 4187} 4188 4189std::vector < std::string > llama_vocab::get_bpe_merges ()const { 4190int max_rank = -1 ; 4191for (const auto & pair :pimpl -> bpe_ranks ) { 4192max_rank = std::max (max_rank ,pair .second ); 4193 } 4194 std::vector < std::string > result (max_rank + 1 ); 4195 4196for (const auto & pair :pimpl -> bpe_ranks ) { 4197result [pair .second ]= pair .first .first + " " + pair .first .second ; 4198 } 4199 4200return result ; 4201} 4202 4203std::vector < char > llama_vocab::get_precompiled_charsmap ()const { 4204return pimpl -> precompiled_charsmap ; 4205} 4206 4207int32_t llama_vocab::tokenize ( 4208const char * text , 4209int32_t text_len , 4210llama_token * tokens , 4211int32_t n_tokens_max , 4212bool add_special , 4213bool parse_special )const { 4214auto res = tokenize (std::string (text ,text_len ),add_special ,parse_special ); 4215if (res .size () >=static_cast < size_t > (std::numeric_limits < int32_t > ::max ())) { 4216LLAMA_LOG_ERROR ("%s: tokenization result size %zu exceeds int32_t limit\n" ,__func__ ,res .size ()); 4217return std::numeric_limits < int32_t > ::min (); 4218 } 4219 4220if (n_tokens_max < (int )res .size ()) { 4221// LLAMA_LOG_ERROR("%s: too many tokens\n", __func__); 4222return - ((int )res .size ()); 4223 } 4224 4225for (size_t i = 0 ;i < res .size ();i ++ ) { 4226tokens [i ]= res [i ]; 4227 } 4228 4229return res .size (); 4230} 4231 4232std::vector < llama_token > llama_vocab::tokenize ( 4233const std::string & raw_text , 4234bool add_special , 4235bool parse_special )const { 4236return pimpl -> tokenize (raw_text ,add_special ,parse_special ); 4237} 4238 4239const std::string & llama_vocab::token_to_piece (llama_token token )const { 4240return pimpl -> token_to_piece (token ); 4241} 4242 4243int32_t llama_vocab::token_to_piece (llama_token token ,char * buf ,int32_t length ,int32_t lstrip ,bool special )const { 4244return pimpl -> token_to_piece (token ,buf ,length ,lstrip ,special ); 4245} 4246 4247int32_t llama_vocab::detokenize ( 4248const llama_token * tokens , 4249int32_t n_tokens , 4250char * text , 4251int32_t text_len_max , 4252bool remove_special , 4253bool unparse_special )const { 4254return pimpl -> detokenize (tokens ,n_tokens ,text ,text_len_max ,remove_special ,unparse_special ); 4255} 4256 4257std::string llama_vocab::detokenize (const std::vector < llama_token > & tokens ,bool special )const { 4258 std::string text ; 4259text .resize (std::max (text .capacity (),tokens .size ())); 4260int32_t n_chars = detokenize (tokens .data (), (int32_t )tokens .size (),& text [0 ], (int32_t )text .size (), false,special ); 4261if (n_chars < 0 ) { 4262text .resize (- n_chars ); 4263n_chars = detokenize (tokens .data (), (int32_t )tokens .size (),& text [0 ], (int32_t )text .size (), false,special ); 4264GGML_ASSERT (n_chars <= (int32_t )text .size ());// whitespace trimming is performed after per-token detokenization 4265 } 4266 4267text .resize (n_chars ); 4268 4269// NOTE: the original tokenizer decodes bytes after collecting the pieces. 4270return text ; 4271} 4272 4273void llama_vocab::print_info ()const { 4274pimpl -> print_info (); 4275} 4276 4277// 4278// interface implementation 4279// 4280 4281int32_t llama_vocab_n_tokens (const struct llama_vocab * vocab ) { 4282return vocab -> n_tokens (); 4283} 4284 4285// deprecated 4286int32_t llama_n_vocab (const struct llama_vocab * vocab ) { 4287return llama_vocab_n_tokens (vocab ); 4288} 4289 4290enum llama_vocab_type llama_vocab_type (const struct llama_vocab * vocab ) { 4291return vocab -> get_type (); 4292} 4293 4294const char * llama_vocab_get_text (const struct llama_vocab * vocab ,llama_token token ) { 4295return vocab -> token_get_text (token ); 4296} 4297 4298float llama_vocab_get_score (const struct llama_vocab * vocab ,llama_token token ) { 4299return vocab -> token_get_score (token ); 4300} 4301 4302enum llama_token_attr llama_vocab_get_attr (const struct llama_vocab * vocab ,llama_token token ) { 4303return vocab -> token_get_attr (token ); 4304} 4305 4306bool llama_vocab_is_eog (const struct llama_vocab * vocab ,llama_token token ) { 4307return vocab -> is_eog (token ); 4308} 4309 4310bool llama_vocab_is_control (const struct llama_vocab * vocab ,llama_token token ) { 4311return vocab -> is_control (token ); 4312} 4313 4314llama_token llama_vocab_bos (const struct llama_vocab * vocab ) { 4315return vocab -> token_bos (); 4316} 4317 4318llama_token llama_vocab_eos (const struct llama_vocab * vocab ) { 4319return vocab -> token_eos (); 4320} 4321 4322llama_token llama_vocab_eot (const struct llama_vocab * vocab ) { 4323return vocab -> token_eot (); 4324} 4325 4326// deprecated 4327llama_token llama_vocab_cls (const struct llama_vocab * vocab ) { 4328return vocab -> token_bos (); 4329} 4330 4331llama_token llama_vocab_sep (const struct llama_vocab * vocab ) { 4332return vocab -> token_sep (); 4333} 4334 4335llama_token llama_vocab_nl (const struct llama_vocab * vocab ) { 4336return vocab -> token_nl (); 4337} 4338 4339llama_token llama_vocab_pad (const struct llama_vocab * vocab ) { 4340return vocab -> token_pad (); 4341} 4342 4343bool llama_vocab_get_add_bos (const struct llama_vocab * vocab ) { 4344return vocab -> get_add_bos (); 4345} 4346 4347bool llama_vocab_get_add_eos (const struct llama_vocab * vocab ) { 4348return vocab -> get_add_eos (); 4349} 4350 4351bool llama_vocab_get_add_sep (const struct llama_vocab * vocab ) { 4352return vocab -> get_add_sep (); 4353} 4354 4355const llama_token * llama_vocab_get_suppress_tokens (const struct llama_vocab * vocab ,int32_t * n_suppress_tokens ) { 4356const std::vector < llama_token > & tokens = vocab -> get_suppress_tokens (); 4357if (n_suppress_tokens ) { 4358* n_suppress_tokens = (int32_t )tokens .size (); 4359 } 4360return tokens .data (); 4361} 4362 4363llama_token llama_vocab_fim_pre (const struct llama_vocab * vocab ) { 4364return vocab -> token_fim_pre (); 4365} 4366 4367llama_token llama_vocab_fim_suf (const struct llama_vocab * vocab ) { 4368return vocab -> token_fim_suf (); 4369} 4370 4371llama_token llama_vocab_fim_mid (const struct llama_vocab * vocab ) { 4372return vocab -> token_fim_mid (); 4373} 4374 4375llama_token llama_vocab_fim_pad (const struct llama_vocab * vocab ) { 4376return vocab -> token_fim_pad (); 4377} 4378 4379llama_token llama_vocab_fim_rep (const struct llama_vocab * vocab ) { 4380return vocab -> token_fim_rep (); 4381} 4382 4383llama_token llama_vocab_fim_sep (const struct llama_vocab * vocab ) { 4384return vocab -> token_fim_sep (); 4385} 4386 4387llama_token llama_vocab_mask (const struct llama_vocab * vocab ) { 4388return vocab -> token_mask (); 4389} 4390 4391// deprecated 4392const char * llama_token_get_text (const struct llama_vocab * vocab ,llama_token token ) { 4393return llama_vocab_get_text (vocab ,token ); 4394} 4395 4396// deprecated 4397float llama_token_get_score (const struct llama_vocab * vocab ,llama_token token ) { 4398return llama_vocab_get_score (vocab ,token ); 4399} 4400 4401// deprecated 4402enum llama_token_attr llama_token_get_attr (const struct llama_vocab * vocab ,llama_token token ) { 4403return llama_vocab_get_attr (vocab ,token ); 4404} 4405 4406// deprecated 4407bool llama_token_is_eog (const struct llama_vocab * vocab ,llama_token token ) { 4408return llama_vocab_is_eog (vocab ,token ); 4409} 4410 4411// deprecated 4412bool llama_token_is_control (const struct llama_vocab * vocab ,llama_token token ) { 4413return llama_vocab_is_control (vocab ,token ); 4414} 4415 4416// deprecated 4417llama_token llama_token_bos (const struct llama_vocab * vocab ) { 4418return llama_vocab_bos (vocab ); 4419} 4420 4421// deprecated 4422llama_token llama_token_eos (const struct llama_vocab * vocab ) { 4423return llama_vocab_eos (vocab ); 4424} 4425 4426// deprecated 4427llama_token llama_token_eot (const struct llama_vocab * vocab ) { 4428return llama_vocab_eot (vocab ); 4429} 4430 4431// deprecated 4432llama_token llama_token_cls (const struct llama_vocab * vocab ) { 4433//return llama_vocab_cls(vocab); 4434return llama_vocab_bos (vocab );// avoid deprecation warning 4435} 4436 4437// deprecated 4438llama_token llama_token_sep (const struct llama_vocab * vocab ) { 4439return llama_vocab_sep (vocab ); 4440} 4441 4442// deprecated 4443llama_token llama_token_nl (const struct llama_vocab * vocab ) { 4444return llama_vocab_nl (vocab ); 4445} 4446 4447// deprecated 4448llama_token llama_token_pad (const struct llama_vocab * vocab ) { 4449return llama_vocab_pad (vocab ); 4450} 4451 4452// deprecated 4453bool llama_add_bos_token (const struct llama_vocab * vocab ) { 4454return llama_vocab_get_add_bos (vocab ); 4455} 4456 4457// deprecated 4458bool llama_add_eos_token (const struct llama_vocab * vocab ) { 4459return llama_vocab_get_add_eos (vocab ); 4460} 4461 4462// deprecated 4463llama_token llama_token_fim_pre (const struct llama_vocab * vocab ) { 4464return llama_vocab_fim_pre (vocab ); 4465} 4466 4467// deprecated 4468llama_token llama_token_fim_suf (const struct llama_vocab * vocab ) { 4469return llama_vocab_fim_suf (vocab ); 4470} 4471 4472// deprecated 4473llama_token llama_token_fim_mid (const struct llama_vocab * vocab ) { 4474return llama_vocab_fim_mid (vocab ); 4475} 4476 4477// deprecated 4478llama_token llama_token_fim_pad (const struct llama_vocab * vocab ) { 4479return llama_vocab_fim_pad (vocab ); 4480} 4481 4482// deprecated 4483llama_token llama_token_fim_rep (const struct llama_vocab * vocab ) { 4484return llama_vocab_fim_rep (vocab ); 4485} 4486 4487// deprecated 4488llama_token llama_token_fim_sep (const struct llama_vocab * vocab ) { 4489return llama_vocab_fim_sep (vocab ); 4490} 4491 4492// 4493// tokenization 4494// 4495 4496int32_t llama_tokenize ( 4497const struct llama_vocab * vocab , 4498const char * text , 4499int32_t text_len , 4500llama_token * tokens , 4501int32_t n_tokens_max , 4502bool add_special , 4503bool parse_special ) { 4504return vocab -> tokenize (text ,text_len ,tokens ,n_tokens_max ,add_special ,parse_special ); 4505} 4506 4507int32_t llama_token_to_piece ( 4508const struct llama_vocab * vocab , 4509llama_token token , 4510char * buf , 4511int32_t length , 4512int32_t lstrip , 4513bool special ) { 4514return vocab -> token_to_piece (token ,buf ,length ,lstrip ,special ); 4515} 4516 4517int32_t llama_detokenize ( 4518const struct llama_vocab * vocab , 4519const llama_token * tokens , 4520int32_t n_tokens , 4521char * text , 4522int32_t text_len_max , 4523bool remove_special , 4524bool unparse_special ) { 4525return vocab -> detokenize (tokens ,n_tokens ,text ,text_len_max ,remove_special ,unparse_special ); 4526}