okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-1b (033cfdd8c) into f-own-int: nothing downloads llama.cppb2de2641f

main
182.1 KiB4526 linesraw
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 {
30    naive_trie() : has_value(false), value(0) {
31    }
32    void insert(const char * key, size_t len, int32_t value = 0) {
33        if (len == 0) {
34            this->has_value = true;
35            this->value = value;
36            return;
37        }
38        char c = key[0];
39        auto res = children.find(c);
40        if (res != children.end()) {
41            res->second.insert(key + 1, len - 1, value);
42        } else {
43            auto res = children.insert(std::make_pair(c, naive_trie()));
44            res.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 {
48        if (len == 0 || offset == len) {
49            return std::make_pair(key, offset);
50        }
51        char c = key[offset];
52        auto res = children.find(c);
53        if (res != children.end()) {
54            return res->second.get_longest_prefix(key, len, offset + 1);
55        }
56
57        return std::make_pair(key, offset);
58    }
59    const struct naive_trie * traverse(const char c) const {
60        auto res = children.find(c);
61        if (res != children.end()) {
62            return &res->second;
63        }
64
65        return NULL;
66    }
67    std::map<char, struct naive_trie> children;
68    bool has_value;
69    llama_token value;
70};
71
72//
73// tokenizers
74//
75
76struct llm_tokenizer {
77    llm_tokenizer() {}
78    virtual ~llm_tokenizer() = default;
79};
80
81struct llm_symbol {
82    using index = int;
83    index prev;
84    index next;
85    const char * text;
86    size_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 {
98    struct comparator {
99        bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
100            return (l.score < r.score) || (l.score == r.score && l.left > r.left);
101        }
102    };
103    using queue_storage = std::vector<llm_bigram_spm>;
104    using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
105    llm_symbol::index left;
106    llm_symbol::index right;
107    float score;
108    size_t size;
109};
110
111struct llm_tokenizer_spm : llm_tokenizer {
112    llm_tokenizer_spm(const llama_vocab & /*vocab*/) {}
113};
114
115struct llm_tokenizer_spm_session {
116    llm_tokenizer_spm_session(const llama_vocab & vocab) : vocab(vocab) {}
117
118    void tokenize(const std::string & text, std::vector<llama_token> & output) {
119        // split string into utf8 chars
120        int index = 0;
121        size_t offs = 0;
122        while (offs < text.size()) {
123            llm_symbol sym;
124            size_t len = unicode_len_utf8(text[offs]);
125            sym.text = text.c_str() + offs;
126            sym.n = std::min(len, text.size() - offs);
127            offs += sym.n;
128            sym.prev = index - 1;
129            sym.next = offs == text.size() ? -1 : index + 1;
130            index++;
131            symbols.emplace_back(sym);
132        }
133
134        // seed the work queue with all possible 2-character tokens.
135        for (int i = 1; i < (int) symbols.size(); ++i) {
136            try_add_bigram(i - 1, i);
137        }
138
139        // keep substituting the highest frequency pairs for as long as we can.
140        while (!work_queue.empty()) {
141            auto bigram = work_queue.top();
142            work_queue.pop();
143
144            auto & left_sym = symbols[bigram.left];
145            auto & right_sym = symbols[bigram.right];
146
147            // if one of the symbols already got merged, skip it.
148            if (left_sym.n == 0 || right_sym.n == 0 ||
149                left_sym.n + right_sym.n != bigram.size) {
150                continue;
151            }
152
153            // merge the right sym into the left one
154            left_sym.n += right_sym.n;
155            right_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
160            left_sym.next = right_sym.next;
161            if (right_sym.next >= 0) {
162                symbols[right_sym.next].prev = bigram.left;
163            }
164
165            // find more substitutions
166            try_add_bigram(left_sym.prev, bigram.left);
167            try_add_bigram(bigram.left, left_sym.next);
168        }
169
170        for (int i = 0; i != -1; i = symbols[i].next) {
171            auto & symbol = symbols[i];
172            resegment(symbol, output);
173        }
174    }
175
176private:
177    void resegment(llm_symbol & symbol, std::vector<llama_token> & output) {
178        auto text = std::string(symbol.text, symbol.n);
179        auto token = vocab.text_to_token(text);
180
181        // Do we need to support is_unused?
182        if (token != LLAMA_TOKEN_NULL) {
183            output.push_back(token);
184            return;
185        }
186
187        const auto p = rev_merge.find(text);
188
189        if (p == rev_merge.end()) {
190            // output any symbols that did not form tokens as bytes.
191            output.reserve(output.size() + symbol.n);
192            for (int j = 0; j < (int)symbol.n; ++j) {
193                llama_token id = vocab.byte_to_token(symbol.text[j]);
194                output.push_back(id);
195            }
196            return;
197        }
198
199        resegment(symbols[p->second.first], output);
200        resegment(symbols[p->second.second], output);
201    }
202
203    void try_add_bigram(int left, int right) {
204        if (left == -1 || right == -1) {
205            return;
206        }
207        const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
208        auto token = vocab.text_to_token(text);
209
210        if (token == LLAMA_TOKEN_NULL) {
211            return;
212        }
213
214        if (static_cast<uint32_t>(token) >= vocab.n_tokens()) {
215            return;
216        }
217
218        const auto & tok_data = vocab.get_token_data(token);
219
220        llm_bigram_spm bigram;
221        bigram.left  = left;
222        bigram.right = right;
223        bigram.score = tok_data.score;
224        bigram.size  = text.size();
225
226        work_queue.push(bigram);
227
228        // Do we need to support is_unused?
229        rev_merge[text] = std::make_pair(left, right);
230    }
231
232    const 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:
252    using std::priority_queue<T, Container, Compare>::priority_queue;
253
254    T pop_move() {
255        T item = std::move(this->c.front());
256        std::pop_heap(this->c.begin(), this->c.end(), this->comp);
257        this->c.pop_back();
258        return item;
259    }
260
261    void pop() =  delete;
262};
263
264struct llm_bigram_bpe {
265    struct comparator {
266        bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
267            return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
268        }
269    };
270
271    using queue_storage = std::vector<llm_bigram_bpe>;
272    using queue = llama_priority_queue<llm_bigram_bpe, queue_storage, comparator>;
273    llm_symbol::index left;
274    llm_symbol::index right;
275    std::string text;
276    int rank;
277    size_t size;
278};
279
280struct llm_tokenizer_bpe : llm_tokenizer {
281    llm_tokenizer_bpe(const llama_vocab & vocab) {
282        GGML_ASSERT(vocab.get_type() == LLAMA_VOCAB_TYPE_BPE);
283        switch (vocab.get_pre_type()) {
284            case LLAMA_VOCAB_PRE_TYPE_LLAMA3:
285                regex_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                };
292                break;
293            case LLAMA_VOCAB_PRE_TYPE_JAIS2:
294                regex_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                };
301                break;
302            case LLAMA_VOCAB_PRE_TYPE_DBRX:
303            case LLAMA_VOCAB_PRE_TYPE_SMAUG:
304                regex_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                };
308                break;
309            case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM:
310                regex_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                };
318                break;
319            case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK3_LLM:
320            case LLAMA_VOCAB_PRE_TYPE_HUNYUAN_DENSE:
321            case LLAMA_VOCAB_PRE_TYPE_JOYAI_LLM:
322            case LLAMA_VOCAB_PRE_TYPE_HY_V4:
323                regex_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                };
328                break;
329            case LLAMA_VOCAB_PRE_TYPE_SPARK2_5:
330                regex_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                };
336                break;
337            case LLAMA_VOCAB_PRE_TYPE_YOUTU:
338                regex_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                };
342                break;
343            case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER:
344                regex_exprs = {
345                    "[\r\n]",
346                    "\\s?\\p{L}+",
347                    "\\s?\\p{P}+",
348                    "[一-龥ࠀ-一가-퟿]+",
349                    "\\p{N}",
350                };
351                break;
352            case LLAMA_VOCAB_PRE_TYPE_FALCON:
353                regex_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                };
358                break;
359            case LLAMA_VOCAB_PRE_TYPE_STARCODER:
360            case LLAMA_VOCAB_PRE_TYPE_REFACT:
361            case LLAMA_VOCAB_PRE_TYPE_COMMAND_R:
362            case LLAMA_VOCAB_PRE_TYPE_SMOLLM:
363            case LLAMA_VOCAB_PRE_TYPE_CODESHELL:
364            case LLAMA_VOCAB_PRE_TYPE_EXAONE:
365            case LLAMA_VOCAB_PRE_TYPE_MINERVA:
366            case LLAMA_VOCAB_PRE_TYPE_MELLUM2:
367                regex_exprs = {
368                    "\\p{N}",
369                    "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
370                };
371                break;
372            case LLAMA_VOCAB_PRE_TYPE_GPT2:
373            case LLAMA_VOCAB_PRE_TYPE_MPT:
374            case LLAMA_VOCAB_PRE_TYPE_OLMO:
375            case LLAMA_VOCAB_PRE_TYPE_JAIS:
376            case LLAMA_VOCAB_PRE_TYPE_TRILLION:
377            case LLAMA_VOCAB_PRE_TYPE_GRANITE_DOCLING:
378                regex_exprs = {
379                    "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
380                };
381                break;
382            case LLAMA_VOCAB_PRE_TYPE_STABLELM2:
383            case LLAMA_VOCAB_PRE_TYPE_QWEN2:
384            case LLAMA_VOCAB_PRE_TYPE_HUNYUAN:
385            case LLAMA_VOCAB_PRE_TYPE_SOLAR_OPEN:
386                regex_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                };
391                break;
392            case LLAMA_VOCAB_PRE_TYPE_QWEN35:
393                regex_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                };
398                break;
399            case LLAMA_VOCAB_PRE_TYPE_PORO:
400            case LLAMA_VOCAB_PRE_TYPE_BLOOM:
401            case LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH:
402                regex_exprs = {
403                    " ?[^(\\s|.,!?…。,、।۔،)]+",
404                };
405                break;
406            case LLAMA_VOCAB_PRE_TYPE_CHATGLM4:
407                regex_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                };
410                break;
411            case LLAMA_VOCAB_PRE_TYPE_VIKING:
412                regex_exprs = {
413                    " ?[^(\\s|.,!?…。,、।۔،)]+",
414                    "\\p{N}",
415                };
416                break;
417            case 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+"
420                regex_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                };
423                break;
424            case 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).
429                regex_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                };
437                break;
438            case LLAMA_VOCAB_PRE_TYPE_GPT4O:
439            case LLAMA_VOCAB_PRE_TYPE_MINIMAX_M2:
440                regex_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                };
445                break;
446            case 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.
451                regex_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                };
454                break;
455            case LLAMA_VOCAB_PRE_TYPE_TINY_AYA:
456                regex_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                };
462                break;
463            case LLAMA_VOCAB_PRE_TYPE_KIMI_K2:
464                regex_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                };
469                break;
470            case LLAMA_VOCAB_PRE_TYPE_SUPERBPE:
471                regex_exprs = {
472                    "\\p{N}+",
473                    "(?=(\\d{3})+(?!\\d))",
474                };
475                break;
476            case LLAMA_VOCAB_PRE_TYPE_BAILINGMOE:
477                regex_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                };
483                break;
484            case LLAMA_VOCAB_PRE_TYPE_SEED_CODER:
485                regex_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                };
490                break;
491            case LLAMA_VOCAB_PRE_TYPE_UFAKZEKA:
492                regex_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                };
496                break;
497            case LLAMA_VOCAB_PRE_TYPE_GROK_2:
498                regex_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                };
503                break;
504            case LLAMA_VOCAB_PRE_TYPE_AFMOE:
505                regex_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                };
514                break;
515            case LLAMA_VOCAB_PRE_TYPE_LAGUNA:
516                regex_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                };
520                break;
521            case LLAMA_VOCAB_PRE_TYPE_EXAONE_MOE:
522                regex_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                };
527                break;
528            case 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.
533                regex_exprs = {
534                    "[^\\n]+|[\\n]+",
535                };
536                byte_encode = false; // uses raw UTF-8, not GPT-2 byte encoding
537                break;
538            case 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.
541                regex_exprs = {
542                    "[^\\n]+|[\\n]+",
543                };
544                byte_encode = false;
545                break;
546            case LLAMA_VOCAB_PRE_TYPE_MINICPM5:
547                regex_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                };
553                break;
554            case LLAMA_VOCAB_PRE_TYPE_WHITESPACE:
555                // whitespace pre-tokenizer (jinaai/jina-embeddings-v2-base-zh)
556                regex_exprs = {
557                    "\\S+",
558                };
559                byte_encode = false;
560                break;
561            default:
562                // default regex for BPE tokenization pre-processing
563                regex_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                };
569                break;
570        }
571    }
572
573    std::vector<std::string> regex_exprs;
574    bool byte_encode = true; // GPT-2 byte encoding; false for SPM-style BPE (raw UTF-8)
575};
576
577struct llm_tokenizer_bpe_session {
578    llm_tokenizer_bpe_session(const llama_vocab & vocab, const llm_tokenizer_bpe & tokenizer) : vocab(vocab), tokenizer(tokenizer) {}
579
580    virtual ~llm_tokenizer_bpe_session() = default;
581
582    static void append(const llama_token token_id, std::vector<llama_token> & output)  {
583        output.push_back(token_id);
584    }
585
586    bool append_bos(std::vector<llama_token> & output) const {
587        if (vocab.get_add_bos()) {
588            GGML_ASSERT(vocab.token_bos() != LLAMA_TOKEN_NULL);
589            output.push_back(vocab.token_bos());
590            return true;
591        }
592        return false;
593    }
594
595    bool append_eos(std::vector<llama_token> & output) const {
596        if (vocab.get_add_eos()) {
597            GGML_ASSERT(vocab.token_eos() != LLAMA_TOKEN_NULL);
598            output.push_back(vocab.token_eos());
599            return true;
600        }
601        return false;
602    }
603
604    void check_double_bos_eos(const std::vector<llama_token> & output) const {
605        if (vocab.get_add_bos() && output.size() >= 2 && output[1] == vocab.token_bos()) {
606            LLAMA_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        }
611        if (vocab.get_add_eos() && output.size() >= 2 && *(output.end()-2) == vocab.token_eos()) {
612            LLAMA_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
619    virtual void tokenize(const std::string & text, std::vector<llama_token> & output) {
620        int final_prev_index = -1;
621        const auto word_collection = unicode_regex_split(text, tokenizer.regex_exprs, tokenizer.byte_encode);
622
623        symbols_final.clear();
624        auto tok_pre = vocab.get_pre_type();
625
626        for (const auto & word : word_collection) {
627            work_queue = llm_bigram_bpe::queue();
628            symbols.clear();
629
630            int index = 0;
631            size_t offset = 0;
632
633            //if (vocab.tokenizer_ignore_merges && vocab.token_to_id.find(word) != vocab.token_to_id.end()) {
634            if (vocab.get_ignore_merges() && vocab.text_to_token(word) != LLAMA_TOKEN_NULL) {
635                symbols.emplace_back(llm_symbol{-1, -1, word.c_str(), word.size()});
636                offset = 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
639                auto tok = vocab.text_to_token(word);
640                if (tok != LLAMA_TOKEN_NULL) {
641                    symbols.emplace_back(llm_symbol{-1, -1, word.c_str(), word.size()});
642                    offset = word.size();
643                }
644            }
645
646            while (offset < word.size()) {
647                llm_symbol sym;
648                size_t char_len = std::min(word.size() - offset, (size_t) unicode_len_utf8(word[offset]));
649                sym.text = word.c_str() + offset;
650                sym.n = char_len;
651                offset += sym.n;
652                sym.prev = index - 1;
653                sym.next = offset == word.size() ? -1 : index + 1;
654                index++;
655                symbols.emplace_back(sym);
656            }
657            for (int i = 1; i < (int) symbols.size(); ++i) {
658                add_new_bigram(i - 1, i);
659            }
660
661            // build token(s)
662            while (!work_queue.empty()) {
663                auto bigram = work_queue.pop_move();
664
665                auto & left_symbol = symbols[bigram.left];
666                auto & right_symbol = symbols[bigram.right];
667
668                if (left_symbol.n == 0 || right_symbol.n == 0) {
669                    continue;
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);
673                if (left_token + right_token != bigram.text) {
674                    continue;  // Skip this bigram if it's outdated
675                }
676
677                // merge the right sym into the left one
678                left_symbol.n += right_symbol.n;
679                right_symbol.n = 0;
680
681                // remove the right sym from the chain
682                left_symbol.next = right_symbol.next;
683                if (right_symbol.next >= 0) {
684                    symbols[right_symbol.next].prev = bigram.left;
685                }
686
687                add_new_bigram(left_symbol.prev, bigram.left);  // left side of current symbol
688                add_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
692            for (auto & sym : symbols) {
693                if (sym.n > 0) {
694                    sym.prev = final_prev_index;
695                    sym.next = -1;
696                    if (final_prev_index != -1) {
697                        symbols_final[final_prev_index].next = symbols_final.size();
698                    }
699                    symbols_final.emplace_back(sym);
700                    final_prev_index = symbols_final.size() - 1;
701                }
702            }
703        }
704
705        symbols = symbols_final;
706
707        if (!symbols.empty()) {
708            for (int i = 0; i != -1; i = symbols[i].next) {
709                auto & symbol = symbols[i];
710                if (symbol.n == 0) {
711                    continue;
712                }
713
714                const std::string str = std::string(symbol.text, symbol.n);
715                const auto token = vocab.text_to_token(str);
716
717                if (token == LLAMA_TOKEN_NULL) {
718                    for (auto j = str.begin(); j != str.end(); ++j) {
719                        llama_token token_multibyte = LLAMA_TOKEN_NULL;
720                        if (tokenizer.byte_encode) {
721                            std::string byte_str(1, *j);
722                            token_multibyte = vocab.text_to_token(byte_str);
723                        } else {
724                            // For non-byte-encoded BPE (e.g. gemma-4), byte tokens use <0xXX> format
725                            static const char * hex = "0123456789ABCDEF";
726                            const uint8_t ch = (uint8_t)*j;
727                            const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
728                            token_multibyte = vocab.text_to_token(buf);
729                        }
730                        if (token_multibyte != LLAMA_TOKEN_NULL) {
731                            output.push_back(token_multibyte);
732                        }
733                    }
734                } else {
735                    output.push_back(token);
736                }
737            }
738        }
739    }
740
741private:
742    void add_new_bigram(int left, int right) {
743        if (left == -1 || right == -1) {
744            return;
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
749        int rank_found = -1;
750
751        rank_found = vocab.find_bpe_rank(left_token, right_token);
752
753        if (rank_found < 0) {
754            return;
755        }
756
757        llm_bigram_bpe bigram;
758
759        bigram.left  = left;
760        bigram.right = right;
761        bigram.text  = left_token + right_token;
762        bigram.size  = left_token.size() + right_token.size();
763        bigram.rank  = rank_found;
764
765        work_queue.push(bigram);
766    }
767
768    const llama_vocab & vocab;
769    const 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 {
781    llm_tokenizer_wpm(const llama_vocab & /*vocab*/) {}
782};
783
784struct llm_tokenizer_wpm_session {
785    llm_tokenizer_wpm_session(const llama_vocab & vocab) : vocab(vocab) {}
786
787    void 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
793        for (const std::string & word : words) {
794            // skip empty words
795            if (word.size() == 0) {
796                continue;
797            }
798
799            // prepend phantom space
800            const std::string word1 = "\xe2\x96\x81" + word;
801            const int n = word1.size();
802
803            const size_t current_tokens = output.size();
804
805            // we're at the start of a new word
806            // move through character position in word
807            for (int i = 0; i < n; ++i) {
808                // loop through possible match length
809                bool match = false;
810                for (int j = std::min(n, i + vocab.max_token_len() + 1); j > i; j--) {
811                    auto id = vocab.text_to_token(word1.substr(i, j - i));
812                    if (id != LLAMA_TOKEN_NULL) {
813                        output.push_back(id);
814                        match = true;
815                        i = j - 1;
816                        break;
817                    }
818                }
819
820                if (!match) { // discard all
821                    output.resize(current_tokens);
822                    break;  // and discard next tokens
823                }
824            }
825
826            // we didn't find any matches for this word
827            if (current_tokens == output.size()) {
828                output.push_back(vocab.token_unk());
829            }
830        }
831    }
832
833    // TODO: reduce string copies by using cpts_offs array
834    static 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);
836        if (normalizer_opts.strip_accents) {
837            cpts = unicode_cpts_normalize_nfd(cpts);
838        }
839        std::vector<std::string> words(1, "");
840
841        for (const uint32_t cpt : cpts) {
842            const auto flags = unicode_cpt_flags_from_cpt(cpt);
843
844            if (flags.is_whitespace) {
845                if (words.back().size()) {  // finish previous word if any
846                    words.emplace_back();
847                }
848                continue;
849            }
850
851            assert (!flags.is_separator);
852            if (cpt == 0 || cpt == 0xFFFD || flags.is_control) {
853                continue;
854            }
855
856            if (normalizer_opts.strip_accents && flags.is_accent_mark) {
857                continue;
858            }
859
860            const std::string s = unicode_cpt_to_utf8(normalizer_opts.lowercase ? unicode_tolower(cpt) : cpt);
861            if (flags.is_punctuation || ( cpt < 0x7F && flags.is_symbol ) || is_chinese_char(cpt)) {
862                if (words.back().size()) {  // finish previous word if any
863                    words.emplace_back();
864                }
865                words.back() = s;       // single char word
866                words.emplace_back();   // start a new word
867            } else {
868                words.back() += s;  // append char to word
869            }
870        }
871
872        if (!words.back().size()) {
873            words.pop_back();
874        }
875
876        return words;
877    }
878
879    static bool is_chinese_char(uint32_t cpt) {
880        return
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:
894    const 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 {
904    llm_tokenizer_ugm(const llama_vocab & vocab, const std::vector<char> & precompiled_charsmap) {
905        if (precompiled_charsmap.size() > 0) {
906            size_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
910            uint32_t xcda_blob_size = *(const uint32_t *) &precompiled_charsmap[0];
911            charsmap_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.
915            xcda_array = (const uint32_t *) &precompiled_charsmap[charsmap_offset];
916            xcda_array_size = xcda_blob_size / sizeof(uint32_t);
917            charsmap_offset += xcda_blob_size;
918
919            // Remaining bytes of precompiled charsmap contain null-terminated
920            // replacement strings for prefixes matched by the XCDA.
921            prefix_replacements = &precompiled_charsmap[charsmap_offset];
922            prefix_replacements_size = precompiled_charsmap.size() - charsmap_offset;
923        }
924
925        for (uint32_t id = 0; id < vocab.n_tokens(); ++id) {
926            const auto & token_data = vocab.get_token_data(id);
927
928            if (vocab.is_normal(id)) {
929                min_score = std::min<float>(min_score, token_data.score);
930                max_score = std::max<float>(max_score, token_data.score);
931            }
932
933            if (vocab.is_normal(id) ||
934                vocab.is_user_defined(id) ||
935                vocab.is_unused(id)) {
936                token_matcher.insert(token_data.text.data(), token_data.text.size(), id);
937            }
938
939            if (vocab.is_user_defined(id)) {
940                user_defined_token_matcher.insert(token_data.text.data(), token_data.text.size());
941            }
942        }
943
944        unknown_token_score = min_score - unknown_token_score_penalty;
945    }
946
947    // escaped space symbol - U+2581 (Lower One Eighth Block)
948    const std::string escaped_space = "\xE2\x96\x81";
949
950    const char * prefix_replacements = NULL;
951    size_t prefix_replacements_size = 0;
952
953    const uint32_t * xcda_array = NULL;
954    size_t xcda_array_size = 0;
955
956    struct naive_trie user_defined_token_matcher;
957
958    float min_score = FLT_MAX;
959    float max_score = -FLT_MAX;
960
961    float unknown_token_score_penalty = 10.0;
962    float unknown_token_score;
963
964    struct naive_trie token_matcher;
965};
966
967struct llm_tokenizer_ugm_session {
968    llm_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    */
983    void tokenize(const std::string & text, std::vector<llama_token> & output) {
984        // get current size of output (for reversal later)
985        size_t output_size = output.size();
986
987        // normalize the input first
988        std::string normalized;
989        normalize(text, &normalized);
990        size_t input_len = normalized.size();
991        if (input_len == 0) {
992            return;
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
998        tokenization_results[0] = { vocab.token_unk(), 0, 0 };
999
1000        for (size_t input_offset = 0; input_offset < input_len;) {
1001            size_t prefix_offset = input_offset;
1002            // calculate how many code units are in the currently processed UTF code point
1003            size_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
1006            bool single_codepoint_token_found = false;
1007            const struct best_tokenization & current_best = tokenization_results[input_offset];
1008            const struct naive_trie * node = tokenizer.token_matcher.traverse(normalized[prefix_offset++]);
1009
1010            while (prefix_offset <= input_len && node != NULL) {
1011                // check if we found valid token in prefix
1012                if (node->has_value) {
1013                    // check if it corresponds to the whole UTF code point
1014                    if (prefix_offset - input_offset == n_utf8_code_units) {
1015                        single_codepoint_token_found = true;
1016                    }
1017                    llama_token token_id = node->value;
1018                    const 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
1024                    const double token_score = vocab.is_user_defined(token_id) ? 0.0 : token_data.score;
1025                    const double challenger_score = current_best.score_sum + token_score;
1026                    struct best_tokenization & current_champ = tokenization_results[prefix_offset];
1027                    if (challenger_score > current_champ.score_sum) {
1028                        struct best_tokenization challenger = { token_id, input_offset, challenger_score };
1029                        current_champ = challenger;
1030                    }
1031                }
1032                node = 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
1037            if (!single_codepoint_token_found) {
1038                const double challenger_score = current_best.score_sum + tokenizer.unknown_token_score;
1039                prefix_offset = input_offset + n_utf8_code_units;
1040                struct best_tokenization & current_champ = tokenization_results[prefix_offset];
1041                if (challenger_score > current_champ.score_sum) {
1042                    struct best_tokenization challenger = { vocab.token_unk(), input_offset, challenger_score };
1043                    current_champ = challenger;
1044                }
1045            }
1046
1047            // move to the next UTF code point
1048            input_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
1053        bool is_prev_unknown = false;
1054        for (struct best_tokenization & tokenization = tokenization_results[input_len]; ; tokenization = tokenization_results[tokenization.input_offset]) {
1055            bool is_unknown = tokenization.token_id == vocab.token_unk();
1056            if (!(is_prev_unknown && is_unknown)) {
1057                output.push_back(tokenization.token_id);
1058            }
1059            if (tokenization.input_offset == 0) {
1060                break;
1061            }
1062            is_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
1072    struct normalization_result {
1073        const char * normalized;
1074        size_t normalized_len;
1075        size_t consumed_input;
1076    };
1077
1078    void normalize(const std::string& input, std::string * normalized) {
1079        normalized->clear();
1080        normalized->reserve(input.size() * 3);
1081
1082        const std::string space = vocab.get_escape_whitespaces() ? tokenizer.escaped_space : " ";
1083
1084        const bool shall_prepend_space = !vocab.get_treat_whitespace_as_suffix() && vocab.get_add_space_prefix();
1085        const bool shall_append_space  =  vocab.get_treat_whitespace_as_suffix() && vocab.get_add_space_prefix();
1086        const bool shall_merge_spaces  =  vocab.get_remove_extra_whitespaces();
1087
1088        bool is_space_prepended = false;
1089        bool processing_non_ws = false;
1090
1091        size_t input_len = input.size();
1092
1093        for (size_t input_offset = 0; input_offset < input_len; ) {
1094            auto norm_res = normalize_prefix(input, input_offset);
1095            for (size_t i = 0; i < norm_res.normalized_len; i++) {
1096                char c = norm_res.normalized[i];
1097                if (c != ' ') {
1098                    if (!processing_non_ws) {
1099                        processing_non_ws = true;
1100                        if ((shall_prepend_space && !is_space_prepended) || shall_merge_spaces) {
1101                            normalized->append(space);
1102                            is_space_prepended = true;
1103                        }
1104                    }
1105                    normalized->push_back(c);
1106                } else {
1107                    if (processing_non_ws) {
1108                        processing_non_ws = false;
1109                    }
1110                    if (!shall_merge_spaces) {
1111                        normalized->append(space);
1112                    }
1113                }
1114            }
1115
1116            input_offset += norm_res.consumed_input;
1117        }
1118
1119        if (shall_append_space) {
1120            normalized->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     */
1133    struct xcda_array_view {
1134    public:
1135        xcda_array_view(const uint32_t * xcda_array, size_t xcda_array_size) : xcda_array(xcda_array), xcda_array_size(xcda_array_size) {
1136        }
1137        uint32_t get_base(size_t index) {
1138            uint32_t packed_node = get_node(index);
1139            return (packed_node >> 10) << ((packed_node & (1U << 9)) >> 6);
1140        }
1141        uint32_t get_lcheck(size_t index) {
1142            uint32_t packed_node = get_node(index);
1143            return packed_node & ((1U << 31) | 0xff);
1144        }
1145        bool get_leaf(size_t index) {
1146            uint32_t packed_node = get_node(index);
1147            return (packed_node >> 8) & 1;
1148        }
1149        uint32_t get_value(size_t index) {
1150            uint32_t packed_node = get_node(index);
1151            return packed_node & ((1U << 31) - 1);
1152        }
1153    private:
1154        uint32_t get_node(size_t index) {
1155            if (index >= xcda_array_size) {
1156                throw std::runtime_error("Index out of array bounds in XCDA array!");
1157            }
1158            return xcda_array[index];
1159        }
1160        const uint32_t * xcda_array;
1161        size_t xcda_array_size;
1162    };
1163
1164    // this structure stores the best tokenization so far at input_offset
1165    struct best_tokenization {
1166        llama_token token_id;
1167        size_t input_offset;
1168        double score_sum;
1169    };
1170
1171    struct normalization_result normalize_prefix(const std::string & input, size_t input_offset) {
1172        if (input_offset == input.size()) {
1173            return { &input[input_offset], 0, 0 };
1174        }
1175
1176        // if input prefix matches some user-defined token return this token as normalization result
1177        auto user_defined_token_match =
1178           tokenizer.user_defined_token_matcher.get_longest_prefix(&input[input_offset], input.size() - input_offset);
1179        if (user_defined_token_match.second > 0) {
1180            return { &input[input_offset], user_defined_token_match.second, user_defined_token_match.second };
1181        }
1182
1183        size_t longest_prefix_length = 0;
1184        size_t longest_prefix_offset = 0;
1185
1186        if (tokenizer.xcda_array_size > 0) {
1187            struct 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
1193            uint32_t node_index = 0;
1194            // get BASE of the root node
1195            node_index = xcda_view.get_base(node_index);
1196            for (size_t prefix_offset = input_offset; prefix_offset < input.size(); prefix_offset++) {
1197                unsigned char c = input[prefix_offset];
1198                if (c == 0) {
1199                    break;
1200                }
1201                node_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
1204                if (xcda_view.get_lcheck(node_index) != c) {
1205                    break;
1206                }
1207                bool is_leaf = xcda_view.get_leaf(node_index);
1208                // get BASE of the current node
1209                node_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
1212                if (is_leaf)
1213                {
1214                    longest_prefix_length = prefix_offset - input_offset + 1;
1215                    // get index of replacement sequence for currently matched input prefix
1216                    longest_prefix_offset = xcda_view.get_value(node_index);
1217                }
1218            }
1219        }
1220
1221        if (longest_prefix_length > 0) {
1222            // we have a match, so return the replacement sequence
1223            if (longest_prefix_offset >= tokenizer.prefix_replacements_size) {
1224                throw std::runtime_error("Index out of array bounds in precompiled charsmap!");
1225            }
1226            const char * prefix_replacement = &(tokenizer.prefix_replacements)[longest_prefix_offset];
1227            size_t max_len = tokenizer.prefix_replacements_size - longest_prefix_offset;
1228            size_t repl_len = 0;
1229            while (repl_len < max_len && prefix_replacement[repl_len] != '\0') {
1230                repl_len++;
1231            }
1232            if (repl_len == max_len) {
1233                throw std::runtime_error("Unterminated string in precompiled charsmap!");
1234            }
1235            return { prefix_replacement, repl_len, longest_prefix_length };
1236        }
1237
1238        // check if the input prefix contains a valid sequence of UTF-8 code units
1239        try {
1240            // if yes, return this sequence unmodified
1241            size_t prefix_offset = input_offset;
1242            unicode_cpt_from_utf8(input, prefix_offset);
1243            return { &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
1246            return { "\xEF\xBF\xBD", 3, 1 };
1247        }
1248    }
1249
1250    const llama_vocab & vocab;
1251    const 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;
1260    output.reserve(escaped.size());
1261
1262    // Parser state
1263    bool escaping = false;
1264    uint8_t hex_remaining = 0;
1265    uint8_t hex_acc = 0;
1266
1267    // Step through characters, performing parsing
1268    for (const char & c : escaped) {
1269        // If we're parsing a hex code, interpret the next character
1270        if (hex_remaining != 0) {
1271            uint8_t value = (c >= 'a') ? (c - 'a' + 10) : (c - '0');
1272            hex_acc = (hex_acc << 4) + value;
1273
1274            hex_remaining -= 1;
1275            if (hex_remaining == 0) {
1276                output.push_back(hex_acc);
1277                hex_acc = 0;
1278            }
1279
1280            continue;
1281        }
1282
1283        // If we got an escape character, interpret it
1284        if (escaping) {
1285            if (c == 't') {
1286                output.push_back('\t');
1287            } else if (c == 'n') {
1288                output.push_back('\n');
1289            } else if (c == 'r') {
1290                output.push_back('\r');
1291            } else if (c == 'x') {
1292                hex_remaining = 2;
1293            } else {
1294                output.push_back(c);
1295            }
1296
1297            escaping = false;
1298            continue;
1299        }
1300
1301        if (c == '\\') {
1302            escaping = true;
1303            continue;
1304        }
1305
1306        output.push_back(c);
1307    }
1308
1309    return output;
1310}
1311
1312struct llm_tokenizer_rwkv : llm_tokenizer {
1313    llm_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
1318        for (uint32_t id = 0; id < vocab.n_tokens(); ++id) {
1319            const auto & data = vocab.get_token_data(id);
1320            const auto text = llama_unescape_rwkv_token(data.text);
1321            token_matcher.insert((const char *) text.data(), text.size(), id);
1322        }
1323    }
1324
1325    struct naive_trie token_matcher;
1326};
1327
1328struct llm_tokenizer_rwkv_session {
1329    llm_tokenizer_rwkv_session(const llama_vocab & vocab, const llm_tokenizer_rwkv & tokenizer) : vocab(vocab), tokenizer(tokenizer) {}
1330
1331    void tokenize(const std::string & text, std::vector<llama_token> & output) {
1332        uint32_t position = 0;
1333        while (position < text.size()) {
1334            const struct naive_trie * node = tokenizer.token_matcher.traverse(text[position]);
1335            if (node == NULL) {
1336                // no matching token found, add unknown token
1337                output.push_back(vocab.token_unk());
1338                position += 1;
1339                continue;
1340            }
1341
1342            // traverse the trie to find the longest matching token
1343            uint32_t token_id = 0;
1344            uint32_t token_length = 0;
1345            while (node != NULL) {
1346                if (node->has_value) {
1347                    token_id = node->value;
1348                    token_length = position + 1;
1349                }
1350                if (position + 1 >= text.size()) {
1351                    break;
1352                }
1353                node = node->traverse(text[++position]);
1354            }
1355
1356            // add the longest matching token
1357            output.push_back(token_id);
1358            position = token_length;
1359        }
1360    }
1361
1362private:
1363    const llama_vocab & vocab;
1364    const llm_tokenizer_rwkv & tokenizer;
1365};
1366
1367struct llm_tokenizer_plamo2 : llm_tokenizer {
1368    llm_tokenizer_plamo2(const llama_vocab & vocab) {
1369        build(vocab);
1370    }
1371
1372    void build(const llama_vocab & vocab) {
1373        // Reset internal structures
1374        tokens_.clear();
1375        bytes_.assign(256, 0);
1376        to_suffix_id_.clear();
1377        table_.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
1383        for (size_t token_id = 0; token_id < vocab.n_tokens(); ++token_id) {
1384            const auto & entry = vocab.get_token_data(token_id);
1385            tokens_.push_back(entry.text);
1386            token_to_id[entry.text] = static_cast<llama_token>(token_id);
1387
1388            // Handle byte tokens
1389            if (vocab.is_byte(token_id)) {
1390                if (entry.text.length() == 6 && entry.text.substr(0, 3) == "<0x" && entry.text.back() == '>') {
1391                    std::string hex_str = entry.text.substr(3, 2);
1392                    if (std::isxdigit(static_cast<unsigned char>(hex_str[0])) && std::isxdigit(static_cast<unsigned char>(hex_str[1]))) {
1393                        int byte_val = std::stoi(hex_str, nullptr, 16);
1394                        bytes_[byte_val] = static_cast<llama_token>(token_id);
1395                    }
1396                }
1397                continue;
1398            }
1399
1400            // Add token and all its suffixes to suffix_to_score
1401            suffix_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);
1405            for (size_t i = 1; i < cpts.size(); ++i) {
1406                std::string suffix;
1407                for (size_t j = i; j < cpts.size(); ++j) {
1408                    suffix += unicode_cpt_to_utf8(cpts[j]);
1409                }
1410                if (suffix_to_score.find(suffix) == suffix_to_score.end()) {
1411                    suffix_to_score[suffix] = std::numeric_limits<float>::quiet_NaN();
1412                }
1413            }
1414        }
1415
1416        // Check that all byte tokens are set
1417        for (int i = 0; i < 256; ++i) {
1418            if (bytes_[i] == 0) {
1419                throw 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;
1425        suffixes.reserve(suffix_to_score.size() + 1);
1426        for (const auto & pair : suffix_to_score) {
1427            suffixes.push_back(pair.first);
1428        }
1429        suffixes.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());
1434            return 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;
1439        int32_t num_pieces = 0;
1440
1441        for (const auto & suffix : suffixes) {
1442            suffix_to_id[suffix] = num_pieces;
1443            if (!suffix.empty()) {
1444                std::vector<uint32_t> cpts = unicode_cpts_from_utf8(suffix);
1445
1446                std::string remaining;
1447                for (size_t i = 1; i < cpts.size(); ++i) {
1448                    remaining += unicode_cpt_to_utf8(cpts[i]);
1449                }
1450
1451                int64_t piece_code = (static_cast<int64_t>(cpts[0]) << 32) | suffix_to_id[remaining];
1452                to_suffix_id_[piece_code] = num_pieces;
1453
1454                // Count number of pieces for this suffix
1455                int32_t pieces_for_suffix = 1; // sentinel row
1456                for (int32_t piece_length = static_cast<int32_t>(cpts.size()); piece_length > 0; --piece_length) {
1457                    std::string piece;
1458                    for (int32_t i = 0; i < piece_length; ++i) {
1459                        piece += unicode_cpt_to_utf8(cpts[i]);
1460                    }
1461                    if (suffix_to_score.find(piece) != suffix_to_score.end()) {
1462                        pieces_for_suffix++;
1463                    }
1464                }
1465                num_pieces += pieces_for_suffix;
1466            } else {
1467                num_pieces++;  // Empty suffix contributes one piece (sentinel row)
1468            }
1469        }
1470
1471        // Build flattened table
1472        table_.resize(num_pieces, std::vector<int32_t>(4, 0));
1473        int32_t table_idx = 0;
1474
1475        for (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);
1478            for (int32_t piece_length = static_cast<int32_t>(cpts.size()); piece_length > 0; --piece_length) {
1479                std::string piece;
1480                for (int32_t i = 0; i < piece_length; ++i) {
1481                    piece += unicode_cpt_to_utf8(cpts[i]);
1482                }
1483
1484                auto score_it = suffix_to_score.find(piece);
1485                if (score_it == suffix_to_score.end()) {
1486                    continue;
1487                }
1488
1489                table_[table_idx][TABLE_PIECE_LENGTH] = piece_length;
1490                auto token_it = token_to_id.find(piece);
1491                table_[table_idx][TABLE_TOKEN_ID] = (token_it != token_to_id.end()) ? token_it->second : -1;
1492
1493                float score = score_it->second;
1494                table_[table_idx][TABLE_SCORE] = std::isfinite(score) ?
1495                    static_cast<int32_t>(std::round(score * 1e4)) : INVALID_SCORE;
1496                table_[table_idx][TABLE_PIECE_ID] = suffix_to_id[piece];
1497
1498                table_idx++;
1499            }
1500
1501            // Add sentinel row
1502            table_[table_idx][TABLE_PIECE_LENGTH] = 1;
1503            table_[table_idx][TABLE_TOKEN_ID] = -1;
1504            table_[table_idx][TABLE_SCORE] = UNKNOWN_SCORE;
1505            table_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)
1512        if (!unicode_data.empty() && unicode_data[0] == 0xFEFF) {
1513            unicode_data.erase(unicode_data.begin());
1514        }
1515
1516        if (unicode_data.empty()) {
1517            return {};
1518        }
1519
1520        const 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);
1524        scores[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
1529        int32_t suffix_id = 0;
1530
1531        // Process from end to beginning
1532        for (int i = static_cast<int>(data_len) - 1; i >= 0; --i) {
1533            uint32_t c = unicode_data[i];
1534
1535            // Find next suffix ID
1536            for (size_t p = suffix_id; p < table_.size(); ++p) {
1537                int64_t piece_code = (static_cast<int64_t>(c) << 32) | table_[p][TABLE_PIECE_ID];
1538                auto it = to_suffix_id_.find(piece_code);
1539                suffix_id = (it != to_suffix_id_.end()) ? it->second : 0;
1540
1541                if (suffix_id > 0 || table_[p][TABLE_SCORE] == UNKNOWN_SCORE) {
1542                    break;
1543                }
1544            }
1545
1546            // Update best path
1547            for (size_t p = suffix_id; p < table_.size(); ++p) {
1548                int32_t score = table_[p][TABLE_SCORE];
1549                if (score > INVALID_SCORE) {
1550                    int32_t piece_length = table_[p][TABLE_PIECE_LENGTH];
1551                    int64_t s = scores[i + piece_length] - score;
1552
1553                    if (s < scores[i]) {
1554                        scores[i] = s;
1555                        path[i][PATH_TOKEN_LENGTH] = piece_length;
1556                        path[i][PATH_TOKEN_ID] = table_[p][TABLE_TOKEN_ID];
1557                        path[i][PATH_NUM_TOKENS] = path[i + piece_length][PATH_NUM_TOKENS] + 1;
1558
1559                        if (score == UNKNOWN_SCORE) {
1560                            // Add UTF-8 byte count
1561                            path[i][PATH_NUM_TOKENS] += (c >= 0x80) + (c >= 0x800) + (c >= 0x10000);
1562                        }
1563                    }
1564                }
1565
1566                if (score == UNKNOWN_SCORE) {
1567                    break;
1568                }
1569            }
1570        }
1571
1572        // Decode the best path
1573        std::vector<llama_token> token_ids;
1574        token_ids.reserve(path[0][PATH_NUM_TOKENS]);
1575
1576        int pos = 0;
1577        while (pos < static_cast<int>(data_len)) {
1578            if (path[pos][PATH_TOKEN_ID] >= 0) {
1579                token_ids.push_back(path[pos][PATH_TOKEN_ID]);
1580            } else {
1581                // Fall back to byte tokens
1582                uint32_t c = unicode_data[pos];
1583                int s = 1 + (c >= 0x80) + (c >= 0x800) + (c >= 0x10000);
1584
1585                for (int i = 0; i < s; ++i) {
1586                    uint8_t b;
1587                    if (s == 1) {
1588                        b = c;
1589                    } else {
1590                        if (i == 0) {
1591                            b = (0xF00 >> s) & 0xFF;
1592                        } else {
1593                            b = 0x80;
1594                        }
1595                    }
1596                    token_ids.push_back(bytes_[b | ((c >> ((s - i - 1) * 6)) & 0x3F)]);
1597                }
1598            }
1599
1600            assert(path[pos][PATH_TOKEN_LENGTH] > 0);
1601            pos += path[pos][PATH_TOKEN_LENGTH];
1602        }
1603
1604        return token_ids;
1605    }
1606private:
1607    // Constants for table structure
1608    static constexpr int32_t TABLE_PIECE_LENGTH = 0;
1609    static constexpr int32_t TABLE_TOKEN_ID     = 1;
1610    static constexpr int32_t TABLE_SCORE        = 2;
1611    static constexpr int32_t TABLE_PIECE_ID     = 3;
1612
1613    // Constants for path array
1614    static constexpr int32_t PATH_TOKEN_LENGTH  = 0;
1615    static constexpr int32_t PATH_TOKEN_ID      = 1;
1616    static constexpr int32_t PATH_NUM_TOKENS    = 2;
1617
1618    // Score constants
1619    static constexpr int32_t INVALID_SCORE = -20000000;
1620    static 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 {
1637    llm_tokenizer_plamo2_session(const llm_tokenizer_plamo2 & tokenizer) : tokenizer(tokenizer) {}
1638
1639    void tokenize(const std::string & text, std::vector<llama_token> & output) {
1640        std::vector<llama_token> tokens = tokenizer.encode(text);
1641        output.insert(output.end(), tokens.begin(), tokens.end());
1642    }
1643
1644private:
1645    const 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 {
1654    llm_tokenizer_hybriddna_session(const llama_vocab & vocab, const llm_tokenizer_bpe & tokenizer) : llm_tokenizer_bpe_session{vocab, tokenizer}, vocab{vocab} {}
1655
1656    void tokenize(const std::string & text, std::vector<llama_token> & output) override {
1657        static const std::string open_tag  = "<dna>";
1658        static const std::string close_tag = "</dna>";
1659
1660        const auto dna_begin_id = vocab.text_to_token(open_tag);
1661        const auto dna_end_id   = vocab.text_to_token(close_tag);
1662        const 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.
1665        if (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);
1667            return;
1668        }
1669
1670        const size_t k = 6;
1671        size_t pos = 0;
1672
1673        while (pos < text.size()) {
1674            const size_t start = text.find(open_tag, pos);
1675            if (start == std::string::npos) {
1676                if (pos < text.size()) {
1677                    llm_tokenizer_bpe_session::tokenize(text.substr(pos), output);
1678                }
1679                break;
1680            }
1681            if (start > pos) {
1682                llm_tokenizer_bpe_session::tokenize(text.substr(pos, start - pos), output);
1683            }
1684            output.push_back(dna_begin_id);
1685
1686            const size_t content_start = start + open_tag.size();
1687            const size_t end           = text.find(close_tag, content_start);
1688            const size_t content_end   = (end == std::string::npos) ? text.size() : end;
1689
1690            emit_dna_kmers(text.substr(content_start, content_end - content_start), k, dna_oov_id, output);
1691
1692            if (end == std::string::npos) {
1693                break;
1694            }
1695            output.push_back(dna_end_id);
1696            pos = end + close_tag.size();
1697        }
1698    }
1699
1700private:
1701    void emit_dna_kmers(const std::string & raw, size_t k, llama_token oov_id, std::vector<llama_token> & output) {
1702        std::string seq = raw;
1703        for (char & c : seq) {
1704            if (c >= 'a' && c <= 'z') {
1705                c = 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>
1711        auto kmer_token = [&](const std::string & kmer) {
1712            const auto tok = vocab.text_to_token(kmer + dna_kmer_marker);
1713            return tok != LLAMA_TOKEN_NULL ? tok : oov_id;
1714        };
1715
1716        size_t i = 0;
1717        for (; i + k <= seq.size(); i += k) {
1718            output.push_back(kmer_token(seq.substr(i, k)));
1719        }
1720        if (i < seq.size()) {
1721            std::string kmer = seq.substr(i);
1722            kmer.append(k - kmer.size(), 'A');
1723            output.push_back(kmer_token(kmer));
1724        }
1725    }
1726
1727    const llama_vocab & vocab;
1728};
1729
1730struct llm_tokenizer_whitespace_session : llm_tokenizer_bpe_session {
1731    llm_tokenizer_whitespace_session(const llama_vocab & vocab, const llm_tokenizer_bpe & tokenizer) : llm_tokenizer_bpe_session{vocab, tokenizer}, vocab{vocab} {}
1732
1733    void tokenize(const std::string & text, std::vector<llama_token> & output) override {
1734        const bool lowercase = vocab.get_normalizer_opts().lowercase;
1735
1736        std::string segment;
1737        auto flush = [&]() {
1738            if (!segment.empty()) {
1739                llm_tokenizer_bpe_session::tokenize(segment, output);
1740                segment.clear();
1741            }
1742        };
1743
1744        for (uint32_t cpt : unicode_cpts_from_utf8(text)) {
1745            // drop whitespace
1746            if (unicode_cpt_flags_from_cpt(cpt).is_whitespace) {
1747                flush();
1748            } else {
1749                segment += unicode_cpt_to_utf8(lowercase ? unicode_tolower(cpt) : cpt);
1750            }
1751        }
1752        flush();
1753    }
1754
1755private:
1756    const llama_vocab & vocab;
1757};
1758
1759//
1760// impl
1761//
1762
1763typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
1764    FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
1765    FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
1766} FRAGMENT_BUFFER_VARIANT_TYPE;
1767
1768struct fragment_buffer_variant {
1769    fragment_buffer_variant(llama_token _token)
1770    :
1771        type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
1772        token(_token),
1773        raw_text(_dummy),
1774        offset(0),
1775        length(0) {}
1776
1777    fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
1778    :
1779        type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
1780        token((llama_token) - 1),
1781        raw_text(_raw_text),
1782        offset(_offset),
1783        length(_length){
1784            GGML_ASSERT(_offset >= 0);
1785            GGML_ASSERT(_length >= 1);
1786            GGML_ASSERT(offset + length <= raw_text.length());
1787        }
1788
1789    const FRAGMENT_BUFFER_VARIANT_TYPE type;
1790    const llama_token token;
1791    const std::string _dummy;
1792    const std::string & raw_text;
1793    const uint64_t offset;
1794    const uint64_t length;
1795};
1796
1797struct llama_vocab::impl {
1798    uint32_t n_token_types = 0; // for BERT-style token types
1799
1800    std::string tokenizer_model;
1801    std::string tokenizer_pre;
1802
1803    enum llama_vocab_type     type     = LLAMA_VOCAB_TYPE_SPM;
1804    enum llama_vocab_pre_type pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
1805
1806    int 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?
1810    llama_token special_bos_id  = 1;
1811    llama_token special_eos_id  = 2;
1812    llama_token special_eot_id  = LLAMA_TOKEN_NULL;
1813    llama_token special_eom_id  = LLAMA_TOKEN_NULL;
1814    llama_token special_unk_id  = 0;
1815    llama_token special_sep_id  = LLAMA_TOKEN_NULL;
1816    llama_token special_pad_id  = LLAMA_TOKEN_NULL;
1817    llama_token special_mask_id = LLAMA_TOKEN_NULL;
1818
1819    llama_token linefeed_id = 13;
1820
1821    // fim tokens
1822    llama_token special_fim_pre_id = LLAMA_TOKEN_NULL;
1823    llama_token special_fim_suf_id = LLAMA_TOKEN_NULL;
1824    llama_token special_fim_mid_id = LLAMA_TOKEN_NULL;
1825    llama_token special_fim_pad_id = LLAMA_TOKEN_NULL;
1826    llama_token special_fim_rep_id = LLAMA_TOKEN_NULL; // repo
1827    llama_token special_fim_sep_id = LLAMA_TOKEN_NULL; // file separator
1828
1829    // tokenizer flags
1830    bool add_space_prefix           = false;
1831    bool add_bos                    = false;
1832    bool add_eos                    = false;
1833    bool add_sep                    = false;
1834    bool ignore_merges              = false;
1835    bool clean_spaces               = false;  // clean_up_tokenization_spaces
1836    bool remove_extra_whitespaces   = false;
1837    bool escape_whitespaces         = true;
1838    bool 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);
1848    struct pair_hash {
1849        size_t operator()(const std::pair<std::string, std::string> & p) const {
1850            return 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
1865    impl(const llama_vocab & vocab) : vocab(vocab) {
1866    }
1867
1868    ~impl() = default;
1869
1870    void load(llama_model_loader & ml, const LLM_KV & kv);
1871
1872    enum llama_vocab_type get_type() const;
1873
1874    std::string type_name() const;
1875
1876    bool is_normal      (llama_token id) const;
1877    bool is_unknown     (llama_token id) const;
1878    bool is_control     (llama_token id) const;
1879    bool is_byte        (llama_token id) const;
1880    bool is_user_defined(llama_token id) const;
1881    bool is_unused      (llama_token id) const;
1882    bool is_eog         (llama_token id) const;
1883
1884    uint8_t token_to_byte(llama_token id) const;
1885
1886    llama_token_attr token_get_attr(llama_token id) const;
1887
1888    void init_tokenizer(enum llama_vocab_type type);
1889
1890    void tokenizer_st_partition(std::forward_list<fragment_buffer_variant> & buffer, bool parse_special) const;
1891
1892    std::string token_to_piece_for_cache(
1893                  llama_token   token,
1894                         bool   special) const;
1895
1896
1897    std::vector<llama_token> tokenize(
1898            const std::string & raw_text,
1899                         bool   add_special,
1900                         bool   parse_special = false) const;
1901
1902    int32_t tokenize(
1903                   const char * text,
1904                      int32_t   text_len,
1905                  llama_token * tokens,
1906                      int32_t   n_tokens_max,
1907                         bool   add_special,
1908                         bool   parse_special) const;
1909
1910    // does not write null-terminator to buf
1911    int32_t token_to_piece(
1912                  llama_token   token,
1913                         char * buf,
1914                      int32_t   length,
1915                      int32_t   lstrip,
1916                         bool   special) const;
1917
1918    // use cached data
1919    const std::string & token_to_piece(llama_token token) const;
1920
1921    int32_t detokenize(
1922            const llama_token * tokens,
1923                      int32_t   n_tokens,
1924                         char * text,
1925                      int32_t   text_len_max,
1926                         bool   remove_special,
1927                         bool   unparse_special) const;
1928
1929    std::string detokenize(
1930            const std::vector<llama_token> & tokens,
1931                                      bool   special) const;
1932
1933    void print_info() const;
1934
1935private:
1936    const llama_vocab & vocab;
1937};
1938
1939void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
1940    struct gguf_context * ctx = ml.metadata;
1941
1942    // determine vocab type
1943    {
1944        ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_model);
1945        ml.get_key(LLM_KV_TOKENIZER_PRE,   tokenizer_pre, false);
1946
1947        ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, n_token_types, false);
1948
1949        if (tokenizer_model == "no_vocab" || tokenizer_model == "none") {
1950            type = LLAMA_VOCAB_TYPE_NONE;
1951
1952            // default special tokens
1953            special_bos_id  = LLAMA_TOKEN_NULL;
1954            special_eos_id  = LLAMA_TOKEN_NULL;
1955            special_unk_id  = LLAMA_TOKEN_NULL;
1956            special_sep_id  = LLAMA_TOKEN_NULL;
1957            special_pad_id  = LLAMA_TOKEN_NULL;
1958            special_mask_id = LLAMA_TOKEN_NULL;
1959            linefeed_id     = LLAMA_TOKEN_NULL;
1960
1961            // read vocab size from metadata
1962            uint32_t n_tokens = 0;
1963            if (ml.get_key(LLM_KV_VOCAB_SIZE, n_tokens, false)) {
1964                LLAMA_LOG_WARN("%s: adding %u dummy tokens\n", __func__, n_tokens);
1965                id_to_token.resize(n_tokens);
1966            }
1967
1968            return;
1969        }
1970
1971        if (tokenizer_model == "llama") {
1972            type = LLAMA_VOCAB_TYPE_SPM;
1973
1974            // default special tokens
1975            special_bos_id  = 1;
1976            special_eos_id  = 2;
1977            special_unk_id  = 0;
1978            special_sep_id  = LLAMA_TOKEN_NULL;
1979            special_pad_id  = LLAMA_TOKEN_NULL;
1980            special_mask_id = LLAMA_TOKEN_NULL;
1981        } else if (tokenizer_model == "bert") {
1982            type = LLAMA_VOCAB_TYPE_WPM;
1983
1984            // default special tokens
1985            special_bos_id  = 101;
1986            special_eos_id  = LLAMA_TOKEN_NULL;
1987            special_unk_id  = 100;
1988            special_sep_id  = 102;
1989            special_pad_id  = 0;
1990            special_mask_id = 103;
1991
1992            add_sep = true;
1993        } else if (tokenizer_model == "gpt2" || tokenizer_model == "hybriddna" || tokenizer_model == "whitespace") {
1994            type = LLAMA_VOCAB_TYPE_BPE;
1995
1996            // read bpe merges and populate bpe ranks
1997            const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
1998            // Kimi-K2 uses custom tokenization without traditional BPE merges
1999            const bool is_kimi_k2 = (tokenizer_pre == "kimi-k2");
2000
2001            if (merges_keyidx == -1) {
2002                if (!is_kimi_k2) {
2003                    throw std::runtime_error("cannot find tokenizer merges in model file\n");
2004                }
2005                // Kimi-K2 doesn't need merges, skip
2006                LLAMA_LOG_INFO("%s: Kimi-K2 tokenizer detected, skipping BPE merges\n", __func__);
2007            } else {
2008                if (gguf_get_kv_type(ctx, merges_keyidx) != GGUF_TYPE_ARRAY ||
2009                    gguf_get_arr_type(ctx, merges_keyidx) != GGUF_TYPE_STRING) {
2010                    throw std::runtime_error(format("invalid gguf type for %s", kv(LLM_KV_TOKENIZER_MERGES).c_str()));
2011                }
2012                const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
2013                for (int i = 0; i < n_merges; i++) {
2014                    const 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
2020                    const size_t pos = word.find(' ', 1);
2021
2022                    if (pos != std::string::npos) {
2023                        first  = word.substr(0, pos);
2024                        second = word.substr(pos + 1);
2025                    }
2026
2027                    bpe_ranks.emplace(std::make_pair(first, second), i);
2028                }
2029            }
2030
2031            // default special tokens
2032            special_bos_id  = 11;
2033            special_eos_id  = 11;
2034            special_unk_id  = LLAMA_TOKEN_NULL;
2035            special_sep_id  = LLAMA_TOKEN_NULL;
2036            special_pad_id  = LLAMA_TOKEN_NULL;
2037            special_mask_id = LLAMA_TOKEN_NULL;
2038        } else if (tokenizer_model == "t5") {
2039            type = LLAMA_VOCAB_TYPE_UGM;
2040
2041            // default special tokens
2042            special_bos_id  = LLAMA_TOKEN_NULL;
2043            special_eos_id  = 1;
2044            special_unk_id  = 2;
2045            special_sep_id  = LLAMA_TOKEN_NULL;
2046            special_pad_id  = 0;
2047            special_mask_id = LLAMA_TOKEN_NULL;
2048
2049            const int precompiled_charsmap_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP).c_str());
2050            if (precompiled_charsmap_keyidx != -1) {
2051                if (gguf_get_kv_type(ctx, precompiled_charsmap_keyidx) != GGUF_TYPE_ARRAY) {
2052                    throw std::runtime_error(format("invalid gguf type for %s", kv(LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP).c_str()));
2053                }
2054                const gguf_type pc_type = gguf_get_arr_type(ctx, precompiled_charsmap_keyidx);
2055                if (pc_type != GGUF_TYPE_INT8 && pc_type != GGUF_TYPE_UINT8) {
2056                    throw std::runtime_error(format("invalid gguf type for %s", kv(LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP).c_str()));
2057                }
2058
2059                const size_t n_precompiled_charsmap = gguf_get_arr_n(ctx, precompiled_charsmap_keyidx);
2060                const char * pc = (const char *) gguf_get_arr_data(ctx, precompiled_charsmap_keyidx);
2061                precompiled_charsmap.assign(pc, pc + n_precompiled_charsmap);
2062                if (precompiled_charsmap.size() < sizeof(uint32_t)) {
2063                    throw std::runtime_error("precompiled_charsmap too small for xcda_blob_size header!");
2064                }
2065                uint32_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
2069                if (*xcda_blob_size + sizeof(uint32_t) >= precompiled_charsmap.size()) {
2070                    throw 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
2074                size_t xcda_array_size = *xcda_blob_size / sizeof(uint32_t);
2075                uint32_t * xcda_array = (uint32_t *) &precompiled_charsmap[sizeof(uint32_t)];
2076                for (size_t i = 0; i < xcda_array_size; ++i) {
2077                    xcda_array[i] = __builtin_bswap32(xcda_array[i]);
2078                }
2079#endif
2080            }
2081        } else if (tokenizer_model == "rwkv") {
2082            type = LLAMA_VOCAB_TYPE_RWKV;
2083
2084            // default special tokens
2085            special_bos_id = LLAMA_TOKEN_NULL;
2086            special_eos_id = LLAMA_TOKEN_NULL;
2087            special_unk_id = LLAMA_TOKEN_NULL;
2088            special_sep_id = LLAMA_TOKEN_NULL;
2089            special_pad_id = LLAMA_TOKEN_NULL;
2090        } else if (tokenizer_model == "test") {
2091            type = LLAMA_VOCAB_TYPE_TEST;
2092
2093            // default special tokens
2094            special_bos_id  = LLAMA_TOKEN_NULL;
2095            special_eos_id  = LLAMA_TOKEN_NULL;
2096            special_unk_id  = LLAMA_TOKEN_NULL;
2097            special_sep_id  = LLAMA_TOKEN_NULL;
2098            special_pad_id  = LLAMA_TOKEN_NULL;
2099            special_mask_id = LLAMA_TOKEN_NULL;
2100        } else if (tokenizer_model == "plamo2") {
2101            type = LLAMA_VOCAB_TYPE_PLAMO2;
2102
2103            // PLaMo-2 default special tokens (these will be overridden by model config)
2104            special_bos_id = 1;  // <|plamo:bos|>
2105            special_eos_id = 2;  // <|plamo:eos|>
2106            special_unk_id = 0;  // <|plamo:unk|>
2107            special_sep_id = LLAMA_TOKEN_NULL;
2108            special_pad_id = 3;  // <|plamo:pad|>
2109            special_mask_id = LLAMA_TOKEN_NULL;
2110        } else if (tokenizer_model == "gemma4") {
2111            type = LLAMA_VOCAB_TYPE_BPE;
2112
2113            // read bpe merges and populate bpe ranks
2114            const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
2115            if (merges_keyidx == -1) {
2116                throw std::runtime_error("cannot find tokenizer merges in model file\n");
2117            }
2118            {
2119                if (gguf_get_kv_type(ctx, merges_keyidx) != GGUF_TYPE_ARRAY ||
2120                    gguf_get_arr_type(ctx, merges_keyidx) != GGUF_TYPE_STRING) {
2121                    throw std::runtime_error(format("invalid gguf type for %s", kv(LLM_KV_TOKENIZER_MERGES).c_str()));
2122                }
2123                const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
2124                for (int i = 0; i < n_merges; i++) {
2125                    const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
2126
2127                    std::string first;
2128                    std::string second;
2129
2130                    const size_t pos = word.find(' ', 1);
2131
2132                    if (pos != std::string::npos) {
2133                        first  = word.substr(0, pos);
2134                        second = word.substr(pos + 1);
2135                    }
2136
2137                    bpe_ranks.emplace(std::make_pair(first, second), i);
2138                }
2139            }
2140
2141            // default special tokens (to be read from GGUF)
2142            special_bos_id  = LLAMA_TOKEN_NULL;
2143            special_eos_id  = LLAMA_TOKEN_NULL;
2144            special_unk_id  = LLAMA_TOKEN_NULL;
2145            special_sep_id  = LLAMA_TOKEN_NULL;
2146            special_pad_id  = LLAMA_TOKEN_NULL;
2147            special_mask_id = LLAMA_TOKEN_NULL;
2148
2149            tokenizer_pre = "gemma4";
2150        } else {
2151            throw std::runtime_error(format("unknown tokenizer: '%s'", tokenizer_model.c_str()));
2152        }
2153
2154        // for now, only BPE models have pre-tokenizers
2155        if (type == LLAMA_VOCAB_TYPE_BPE) {
2156            add_space_prefix = false;
2157            escape_whitespaces = false;
2158            clean_spaces = true;
2159            if (tokenizer_pre.empty()) {
2160                LLAMA_LOG_WARN("%s: missing pre-tokenizer type, using: 'default'\n", __func__);
2161                LLAMA_LOG_WARN("%s:                                             \n", __func__);
2162                LLAMA_LOG_WARN("%s: ************************************        \n", __func__);
2163                LLAMA_LOG_WARN("%s: GENERATION QUALITY WILL BE DEGRADED!        \n", __func__);
2164                LLAMA_LOG_WARN("%s: CONSIDER REGENERATING THE MODEL             \n", __func__);
2165                LLAMA_LOG_WARN("%s: ************************************        \n", __func__);
2166                LLAMA_LOG_WARN("%s:                                             \n", __func__);
2167                pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
2168            } else if (tokenizer_pre == "default") {
2169                pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
2170            } else if (tokenizer_pre == "minicpm5") {
2171                pre_type = LLAMA_VOCAB_PRE_TYPE_MINICPM5;
2172                ignore_merges = true;
2173            } else if (
2174                    tokenizer_pre == "llama3"   ||
2175                    tokenizer_pre == "llama-v3" ||
2176                    tokenizer_pre == "llama-bpe"||
2177                    tokenizer_pre == "falcon3"  ||
2178                    tokenizer_pre == "falcon-h1" ||
2179                    tokenizer_pre == "pixtral"  ||
2180                    tokenizer_pre == "midm-2.0" ||
2181                    tokenizer_pre == "lfm2"     ||
2182                    tokenizer_pre == "jina-v5-nano") {
2183                pre_type = LLAMA_VOCAB_PRE_TYPE_LLAMA3;
2184                ignore_merges = true;
2185                add_bos = true;
2186            } else if (
2187                    tokenizer_pre == "deepseek-llm") {
2188                pre_type = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM;
2189                clean_spaces = false;
2190            } else if (
2191                    tokenizer_pre == "deepseek-coder") {
2192                pre_type = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER;
2193                clean_spaces = false;
2194            } else if (
2195                    tokenizer_pre == "deepseek-v3") {
2196                pre_type = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK3_LLM;
2197                clean_spaces = false;
2198            } else if (
2199                    tokenizer_pre == "spark2_5") {
2200                pre_type = LLAMA_VOCAB_PRE_TYPE_SPARK2_5;
2201                clean_spaces = false;
2202            } else if (
2203                    tokenizer_pre == "youtu") {
2204                pre_type = LLAMA_VOCAB_PRE_TYPE_YOUTU;
2205                clean_spaces = false;
2206                ignore_merges = true;
2207            } else if (
2208                    tokenizer_pre == "falcon") {
2209                pre_type = LLAMA_VOCAB_PRE_TYPE_FALCON;
2210            } else if (
2211                    tokenizer_pre == "mpt") {
2212                pre_type = LLAMA_VOCAB_PRE_TYPE_MPT;
2213            } else if (
2214                    tokenizer_pre == "starcoder") {
2215                pre_type = LLAMA_VOCAB_PRE_TYPE_STARCODER;
2216            } else if (
2217                    tokenizer_pre == "gpt-2"   ||
2218                    tokenizer_pre == "phi-2"   ||
2219                    tokenizer_pre == "jina-es" ||
2220                    tokenizer_pre == "jina-de" ||
2221                    tokenizer_pre == "gigachat"   ||
2222                    tokenizer_pre == "jina-v2-es" ||
2223                    tokenizer_pre == "jina-v2-de" ||
2224                    tokenizer_pre == "a.x-4.0" ||
2225                    tokenizer_pre == "mellum"  ||
2226                    tokenizer_pre == "modern-bert") {
2227                pre_type = LLAMA_VOCAB_PRE_TYPE_GPT2;
2228            } else if (
2229                    tokenizer_pre == "jais-2") {
2230                pre_type = LLAMA_VOCAB_PRE_TYPE_JAIS2;
2231            } else if (
2232                    tokenizer_pre == "gemma4" ||
2233                    tokenizer_pre == "granite-embed-multi-311m") {
2234                pre_type = LLAMA_VOCAB_PRE_TYPE_GEMMA4;
2235                escape_whitespaces = true;
2236            } else if (
2237                    tokenizer_pre == "sarvam-moe") {
2238                pre_type = LLAMA_VOCAB_PRE_TYPE_SARVAM_MOE;
2239                escape_whitespaces = true;
2240                clean_spaces = false;
2241            } else if (
2242                    tokenizer_pre == "jina-v1-en" ||
2243                    tokenizer_pre == "jina-v2-code" ||
2244                    tokenizer_pre == "roberta-bpe") {
2245                pre_type = LLAMA_VOCAB_PRE_TYPE_GPT2;
2246                add_sep = true;
2247            } else if (
2248                    tokenizer_pre == "whitespace") {
2249                pre_type = LLAMA_VOCAB_PRE_TYPE_WHITESPACE;
2250                normalizer_opts.lowercase = false;
2251            } else if (
2252                    tokenizer_pre == "refact") {
2253                pre_type = LLAMA_VOCAB_PRE_TYPE_REFACT;
2254            } else if (
2255                tokenizer_pre == "command-r") {
2256                pre_type = LLAMA_VOCAB_PRE_TYPE_COMMAND_R;
2257                clean_spaces = false;
2258            } else if (
2259                    tokenizer_pre == "qwen2" ||
2260                    tokenizer_pre == "deepseek-r1-qwen" ||
2261                    tokenizer_pre == "kormo" ||
2262                    tokenizer_pre == "f2llmv2") {
2263                pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN2;
2264                clean_spaces = false;
2265            } else if (
2266                    tokenizer_pre == "qwen35") {
2267                pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN35;
2268                clean_spaces = false;
2269            } else if (
2270                tokenizer_pre == "stablelm2") {
2271                pre_type = LLAMA_VOCAB_PRE_TYPE_STABLELM2;
2272            } else if (
2273                tokenizer_pre == "olmo") {
2274                pre_type = LLAMA_VOCAB_PRE_TYPE_OLMO;
2275            } else if (
2276                tokenizer_pre == "dbrx") {
2277                pre_type = LLAMA_VOCAB_PRE_TYPE_DBRX;
2278            } else if (
2279                tokenizer_pre == "smaug-bpe") {
2280                pre_type = LLAMA_VOCAB_PRE_TYPE_SMAUG;
2281            } else if (
2282                tokenizer_pre == "poro-chat") {
2283                pre_type = LLAMA_VOCAB_PRE_TYPE_PORO;
2284                clean_spaces = false;
2285            } else if (
2286                tokenizer_pre == "glm4" ||
2287                tokenizer_pre == "chatglm-bpe") {
2288                pre_type = LLAMA_VOCAB_PRE_TYPE_CHATGLM4;
2289                special_bos_id = LLAMA_TOKEN_NULL;
2290            } else if (
2291                tokenizer_pre == "viking") {
2292                pre_type = LLAMA_VOCAB_PRE_TYPE_VIKING;
2293                clean_spaces = false;
2294            } else if (
2295                tokenizer_pre == "jais") {
2296                pre_type = LLAMA_VOCAB_PRE_TYPE_JAIS;
2297            } else if (
2298                tokenizer_pre == "tekken") {
2299                pre_type = LLAMA_VOCAB_PRE_TYPE_TEKKEN;
2300                clean_spaces = false;
2301                ignore_merges = true;
2302                add_bos = true;
2303            } else if (
2304                tokenizer_pre == "smollm") {
2305                pre_type = LLAMA_VOCAB_PRE_TYPE_SMOLLM;
2306                clean_spaces = false;
2307            } else if (
2308                tokenizer_pre == "codeshell") {
2309                pre_type = LLAMA_VOCAB_PRE_TYPE_CODESHELL;
2310            } else if (
2311                tokenizer_pre == "bloom") {
2312                pre_type = LLAMA_VOCAB_PRE_TYPE_BLOOM;
2313            } else if (
2314                tokenizer_pre == "gpt3-finnish") {
2315                pre_type = LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH;
2316            } else if (
2317                tokenizer_pre == "exaone") {
2318                pre_type = LLAMA_VOCAB_PRE_TYPE_EXAONE;
2319            } else if (
2320                tokenizer_pre == "exaone4") {
2321                pre_type = LLAMA_VOCAB_PRE_TYPE_GPT2;
2322            } else if (
2323                tokenizer_pre == "exaone-moe") {
2324                pre_type = LLAMA_VOCAB_PRE_TYPE_EXAONE_MOE;
2325            } else if (
2326                tokenizer_pre == "chameleon") {
2327                pre_type = LLAMA_VOCAB_PRE_TYPE_CHAMELEON;
2328                add_bos = true;
2329                clean_spaces = false;
2330            } else if (
2331                tokenizer_pre == "minerva-7b") {
2332                pre_type = LLAMA_VOCAB_PRE_TYPE_MINERVA;
2333            } else if (
2334                tokenizer_pre == "megrez") {
2335                pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN2;
2336            } else if (
2337                tokenizer_pre == "gpt-4o" ||
2338                tokenizer_pre == "llama4" ||
2339                tokenizer_pre == "kanana2" ||
2340                tokenizer_pre == "talkie") {
2341                pre_type = LLAMA_VOCAB_PRE_TYPE_GPT4O;
2342                clean_spaces = false;
2343            } else if (
2344                tokenizer_pre == "granite-embed-multi-97m") {
2345                pre_type = LLAMA_VOCAB_PRE_TYPE_GRANITE_EMB_MULTI;
2346                clean_spaces = false;
2347                ignore_merges = true;
2348            } else if (
2349                tokenizer_pre == "tiny_aya" ||
2350                tokenizer_pre == "cohere2moe") {
2351                pre_type = LLAMA_VOCAB_PRE_TYPE_TINY_AYA;
2352                clean_spaces = false;
2353            } else if (
2354                tokenizer_pre == "superbpe") {
2355                pre_type = LLAMA_VOCAB_PRE_TYPE_SUPERBPE;
2356                clean_spaces = false;
2357            } else if (
2358                tokenizer_pre == "trillion") {
2359                pre_type = LLAMA_VOCAB_PRE_TYPE_TRILLION;
2360                clean_spaces = false;
2361            } else if (
2362                tokenizer_pre == "granite-docling") {
2363                pre_type = LLAMA_VOCAB_PRE_TYPE_GRANITE_DOCLING;
2364                clean_spaces = false;
2365            } else if (
2366                tokenizer_pre == "bailingmoe" ||
2367                tokenizer_pre == "bailingmoe2" ||
2368                tokenizer_pre == "llada-moe") {
2369                pre_type = LLAMA_VOCAB_PRE_TYPE_BAILINGMOE;
2370                clean_spaces = false;
2371            } else if (
2372                tokenizer_pre == "seed-coder") {
2373                pre_type = LLAMA_VOCAB_PRE_TYPE_SEED_CODER;
2374                clean_spaces = false;
2375            } else if (
2376                tokenizer_pre == "hunyuan") {
2377                pre_type = LLAMA_VOCAB_PRE_TYPE_HUNYUAN;
2378                clean_spaces = false;
2379            } else if (
2380                tokenizer_pre == "hunyuan-dense") {
2381                pre_type = LLAMA_VOCAB_PRE_TYPE_HUNYUAN_DENSE;
2382                clean_spaces = false;
2383            } else if (
2384                tokenizer_pre == "hy_v4") {
2385                pre_type = LLAMA_VOCAB_PRE_TYPE_HY_V4;
2386                clean_spaces = false;
2387            } else if (
2388                tokenizer_pre == "joyai-llm") {
2389                pre_type = LLAMA_VOCAB_PRE_TYPE_JOYAI_LLM;
2390                clean_spaces = false;
2391            } else if (
2392                tokenizer_pre == "kimi-k2") {
2393                pre_type = LLAMA_VOCAB_PRE_TYPE_KIMI_K2;
2394                clean_spaces = false;
2395            } else if (
2396                tokenizer_pre == "ufakzeka") {
2397                pre_type = LLAMA_VOCAB_PRE_TYPE_UFAKZEKA;
2398                clean_spaces = false;
2399            } else if (
2400                tokenizer_pre == "grok-2") {
2401                pre_type = LLAMA_VOCAB_PRE_TYPE_GROK_2;
2402                clean_spaces = false;
2403            } else if (
2404                tokenizer_pre == "afmoe") {
2405                pre_type = LLAMA_VOCAB_PRE_TYPE_AFMOE;
2406                clean_spaces = false;
2407            } else if (
2408                tokenizer_pre == "laguna") {
2409                pre_type = LLAMA_VOCAB_PRE_TYPE_LAGUNA;
2410                clean_spaces = false;
2411            } else if (
2412                tokenizer_pre == "minimax-m2") {
2413                pre_type = LLAMA_VOCAB_PRE_TYPE_MINIMAX_M2;
2414                clean_spaces = false;
2415            } else if (
2416                tokenizer_pre == "solar-open") {
2417                pre_type = LLAMA_VOCAB_PRE_TYPE_SOLAR_OPEN;
2418                clean_spaces = false;
2419            } else if (
2420                tokenizer_pre == "mellum2") {
2421                pre_type = LLAMA_VOCAB_PRE_TYPE_MELLUM2;
2422            } else {
2423                throw std::runtime_error(format("unknown pre-tokenizer type: '%s'", tokenizer_pre.c_str()));
2424            }
2425        } else if (type == LLAMA_VOCAB_TYPE_SPM) {
2426            pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
2427            add_space_prefix = true;
2428            clean_spaces = false;
2429            add_bos = true;
2430            add_eos = false;
2431        } else if (type == LLAMA_VOCAB_TYPE_WPM) {
2432            pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
2433            add_space_prefix = false;
2434            clean_spaces = true;
2435            add_bos = true;
2436            add_eos = false;
2437            add_sep = true;
2438        } else if (type == LLAMA_VOCAB_TYPE_UGM) {
2439            pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
2440            add_bos = false;
2441            add_eos = true;
2442        } else if (type == LLAMA_VOCAB_TYPE_RWKV) {
2443            pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
2444            add_space_prefix = false;
2445            clean_spaces = false;
2446            add_bos = false;
2447            add_eos = false;
2448        } else {
2449            pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
2450        }
2451
2452        ml.get_key(LLM_KV_TOKENIZER_ADD_PREFIX,      add_space_prefix,         false);
2453        ml.get_key(LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, remove_extra_whitespaces, false);
2454    }
2455
2456    const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
2457    if (token_idx == -1) {
2458        throw std::runtime_error("cannot find tokenizer vocab in model file\n");
2459    }
2460
2461    if (gguf_get_kv_type(ctx, token_idx) != GGUF_TYPE_ARRAY ||
2462        gguf_get_arr_type(ctx, token_idx) != GGUF_TYPE_STRING) {
2463        throw std::runtime_error(format("invalid gguf type for %s", kv(LLM_KV_TOKENIZER_LIST).c_str()));
2464    }
2465
2466    const uint32_t n_tokens = gguf_get_arr_n(ctx, token_idx);
2467
2468    const float * scores = nullptr;
2469    const int * iscores = nullptr;
2470    const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
2471    if (score_idx != -1) {
2472        const gguf_type kv_type = gguf_get_kv_type(ctx, score_idx);
2473        const gguf_type arr_type = kv_type == GGUF_TYPE_ARRAY ? gguf_get_arr_type(ctx, score_idx) : GGUF_TYPE_COUNT;
2474        if (arr_type != GGUF_TYPE_INT32 &&
2475            arr_type != GGUF_TYPE_FLOAT32) {
2476            throw std::runtime_error(format("invalid gguf type for %s", kv(LLM_KV_TOKENIZER_SCORES).c_str()));
2477        }
2478        const uint32_t n_scores = gguf_get_arr_n(ctx, score_idx);
2479        if (n_scores < n_tokens) {
2480            throw std::runtime_error("Index out of array bounds for scores (" + std::to_string(n_scores) + " < " + std::to_string(n_tokens) + ")\n");
2481        }
2482        if (arr_type == GGUF_TYPE_INT32) {
2483            iscores = (const int *) gguf_get_arr_data(ctx, score_idx);
2484        } else {
2485            scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
2486        }
2487    }
2488
2489    const int * toktypes = nullptr;
2490    const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
2491    if (toktype_idx != -1) {
2492        if (gguf_get_kv_type(ctx, toktype_idx) != GGUF_TYPE_ARRAY ||
2493            gguf_get_arr_type(ctx, toktype_idx) != GGUF_TYPE_INT32) {
2494            throw std::runtime_error(format("invalid gguf type for %s", kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str()));
2495        }
2496        const uint32_t n_toktypes = gguf_get_arr_n(ctx, toktype_idx);
2497        if (n_toktypes < n_tokens) {
2498            throw std::runtime_error("Index out of array bounds for toktypes (" + std::to_string(n_toktypes) + " < " + std::to_string(n_tokens) + ")\n");
2499        }
2500        toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
2501    }
2502
2503    id_to_token.resize(n_tokens);
2504
2505    for (uint32_t i = 0; i < n_tokens; i++) {
2506        std::string word = gguf_get_arr_str(ctx, token_idx, i);
2507        if (word.empty()) {
2508            LLAMA_LOG_WARN("%s: empty token at index %u\n", __func__, i);
2509            word = "[EMPTY_" + std::to_string(i) + "]";
2510        }
2511
2512        token_to_id[word] = i;
2513        max_token_len = std::max(max_token_len, (int) word.size());
2514
2515        auto & token_data = id_to_token[i];
2516        token_data.text  = std::move(word);
2517        if (scores) {
2518            token_data.score = scores[i];
2519        } else if (iscores) {
2520            token_data.score = static_cast<float>(iscores[i]);
2521        } else {
2522            token_data.score = 0.0f;
2523        }
2524        token_data.attr  = LLAMA_TOKEN_ATTR_NORMAL;
2525
2526        if (toktypes) {  //TODO: remove, required until per token attributes are available from GGUF file
2527            switch(toktypes[i]) {
2528                case LLAMA_TOKEN_TYPE_UNKNOWN:      token_data.attr = LLAMA_TOKEN_ATTR_UNKNOWN;      break;
2529                case LLAMA_TOKEN_TYPE_UNUSED:       token_data.attr = LLAMA_TOKEN_ATTR_UNUSED;       break;
2530                case LLAMA_TOKEN_TYPE_NORMAL:       token_data.attr = LLAMA_TOKEN_ATTR_NORMAL;       break;
2531                case LLAMA_TOKEN_TYPE_CONTROL:      token_data.attr = LLAMA_TOKEN_ATTR_CONTROL;      break;
2532                case LLAMA_TOKEN_TYPE_USER_DEFINED: token_data.attr = LLAMA_TOKEN_ATTR_USER_DEFINED; break;
2533                case LLAMA_TOKEN_TYPE_BYTE:         token_data.attr = LLAMA_TOKEN_ATTR_BYTE;         break;
2534                case LLAMA_TOKEN_TYPE_UNDEFINED:    token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED;    break;
2535                default:                            token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED;    break;
2536            }
2537        }
2538    }
2539    GGML_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.
2544    if (tokenizer_model == "hybriddna") {
2545        const auto idx = token_to_id.find("<oov>");
2546        if (idx != token_to_id.end()) {
2547            auto it = id_to_token.begin() + idx->second + 1;
2548            for (; it != id_to_token.end(); ++it) {
2549                std::string & text = it->text;
2550                if (text.size() > dna_kmer_marker.size()
2551                        && text.compare(text.size() - dna_kmer_marker.size(), dna_kmer_marker.size(), dna_kmer_marker) == 0) {
2552                    text.erase(text.size() - dna_kmer_marker.size());
2553                }
2554            }
2555        }
2556    }
2557
2558    init_tokenizer(type);
2559
2560    // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
2561    if (type == LLAMA_VOCAB_TYPE_SPM) {
2562        try {
2563            linefeed_id = vocab.byte_to_token('\n');
2564        } catch (const std::exception & e) {
2565            LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
2566            linefeed_id = special_pad_id;
2567        }
2568    } else if (type == LLAMA_VOCAB_TYPE_WPM) {
2569        linefeed_id = special_pad_id;
2570    } else if (type == LLAMA_VOCAB_TYPE_RWKV) {
2571        const std::vector<int> ids = tokenize("\n", false);
2572        GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
2573        linefeed_id = ids[0];
2574    } else {
2575        const std::vector<int> ids = tokenize("\n", false);
2576
2577        //GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
2578        if (ids.empty()) {
2579            LLAMA_LOG_WARN("%s: model vocab missing newline token, using special_pad_id instead\n", __func__);
2580            linefeed_id = special_pad_id;
2581        } else {
2582            linefeed_id = ids[0];
2583        }
2584    }
2585
2586    // special tokens
2587    {
2588        const 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
2610        for (const auto & it : special_token_types) {
2611            const std::string & key = kv(std::get<0>(it));
2612            int32_t & id = std::get<1>(it);
2613
2614            if (id >= 0 && static_cast<size_t>(id) >= id_to_token.size()) {
2615                LLAMA_LOG_WARN("%s: default special token '%s' = %d out of vocab range, disabling\n",
2616                    __func__, key.c_str(), id);
2617                id = LLAMA_TOKEN_NULL;
2618            }
2619
2620            uint32_t new_id;
2621            if (!ml.get_key(std::get<0>(it), new_id, false)) {
2622                continue;
2623            }
2624            if (new_id >= id_to_token.size()) {
2625                LLAMA_LOG_WARN("%s: bad special token: '%s' = %u, using default id %d\n",
2626                    __func__, key.c_str(), new_id, id);
2627            } else {
2628                id = new_id;
2629            }
2630        }
2631
2632        // Handle add_bos, add_eos and add_sep
2633        {
2634            bool temp = true;
2635
2636            if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
2637                add_bos = temp;
2638            }
2639            if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
2640                add_eos = temp;
2641            }
2642            if (ml.get_key(LLM_KV_TOKENIZER_ADD_SEP, temp, false)) {
2643                add_sep = temp;
2644            }
2645
2646            // workaround for Gemma 4
2647            // ref: https://github.com/ggml-org/llama.cpp/pull/21500
2648            if (pre_type == LLAMA_VOCAB_PRE_TYPE_GEMMA4 && !add_bos) {
2649                add_bos = true;
2650
2651                LLAMA_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
2656        ml.get_key(LLM_KV_TOKENIZER_NORMALIZER_LOWERCASE,     normalizer_opts.lowercase,     false);
2657        normalizer_opts.strip_accents = normalizer_opts.lowercase;
2658        ml.get_key(LLM_KV_TOKENIZER_NORMALIZER_STRIP_ACCENTS, normalizer_opts.strip_accents, false);
2659
2660        // suppress tokens
2661        {
2662            const int suppress_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SUPPRESS_TOKENS).c_str());
2663            if (suppress_idx != -1) {
2664                if (gguf_get_kv_type(ctx, suppress_idx) != GGUF_TYPE_ARRAY ||
2665                    gguf_get_arr_type(ctx, suppress_idx) != GGUF_TYPE_INT32) {
2666                    throw std::runtime_error(format("invalid gguf type for %s", kv(LLM_KV_TOKENIZER_SUPPRESS_TOKENS).c_str()));
2667                }
2668                const int n = gguf_get_arr_n(ctx, suppress_idx);
2669                const int32_t * data = (const int32_t *) gguf_get_arr_data(ctx, suppress_idx);
2670                // drop out-of-range ids
2671                suppress_tokens.reserve(n);
2672                for (int i = 0; i < n; ++i) {
2673                    const int32_t id = data[i];
2674                    if (id >= 0 && id < (int) id_to_token.size()) {
2675                        suppress_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
2685        for (const auto & t : token_to_id) {
2686            auto & attr = id_to_token[t.second].attr;
2687
2688            // find EOT token: "<|eot_id|>", "<|im_end|>", "<end_of_turn>", etc.
2689            if (special_eot_id == LLAMA_TOKEN_NULL) {
2690                if (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                   ) {
2703                    special_eot_id = t.second;
2704                    if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
2705                        LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
2706                                __func__, t.second, t.first.c_str());
2707                        attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL);
2708                    }
2709                }
2710            }
2711
2712            // find EOM token: "<|eom_id|>"
2713            if (special_eom_id == LLAMA_TOKEN_NULL) {
2714                if (false
2715                        || t.first == "<|eom_id|>"
2716                        ) {
2717                    special_eom_id = t.second;
2718                    if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
2719                        LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
2720                                __func__, t.second, t.first.c_str());
2721                        attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL);
2722                    }
2723                }
2724            }
2725
2726            // find FIM_PRE token: "<|fim_prefix|>", "<fim-prefix>", "<PRE>", etc.
2727            if (special_fim_pre_id == LLAMA_TOKEN_NULL) {
2728                if (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                        ) {
2738                    special_fim_pre_id = t.second;
2739                    if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
2740                        LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
2741                                __func__, t.second, t.first.c_str());
2742                        attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL);
2743                    }
2744                }
2745            }
2746
2747            // find FIM_SUF token: "<|fim_suffix|>", "<fim-suffix>", "<SUF>", etc.
2748            if (special_fim_suf_id == LLAMA_TOKEN_NULL) {
2749                if (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                        ) {
2759                    special_fim_suf_id = t.second;
2760                    if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
2761                        LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
2762                                __func__, t.second, t.first.c_str());
2763                        attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL);
2764                    }
2765                }
2766            }
2767
2768            // find FIM_MID token: "<|fim_middle|>", "<fim-middle>", "<MID>", etc.
2769            if (special_fim_mid_id == LLAMA_TOKEN_NULL) {
2770                if (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                        ) {
2780                    special_fim_mid_id = t.second;
2781                    if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
2782                        LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
2783                                __func__, t.second, t.first.c_str());
2784                        attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL);
2785                    }
2786                }
2787            }
2788
2789            // find FIM_PAD token: "<|fim_pad|>", "<fim-pad>", "<PAD>", etc.
2790            if (special_fim_pad_id == LLAMA_TOKEN_NULL) {
2791                if (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                        ) {
2798                    special_fim_pad_id = t.second;
2799                    if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
2800                        LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
2801                                __func__, t.second, t.first.c_str());
2802                        attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL);
2803                    }
2804                }
2805            }
2806
2807            // find FIM_REP token: "<|fim_repo|>", "<fim-repo>", "<REP>", etc.
2808            if (special_fim_rep_id == LLAMA_TOKEN_NULL) {
2809                if (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                        ) {
2816                    special_fim_rep_id = t.second;
2817                    if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
2818                        LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
2819                                __func__, t.second, t.first.c_str());
2820                        attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL);
2821                    }
2822                }
2823            }
2824
2825            // find FIM_SEP token: "<|file_sep|>"
2826            if (special_fim_sep_id == LLAMA_TOKEN_NULL) {
2827                if (false
2828                        || t.first == "<|file_sep|>" // Qwen
2829                        ) {
2830                    special_fim_sep_id = t.second;
2831                    if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
2832                        LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
2833                                __func__, t.second, t.first.c_str());
2834                        attr = (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        {
2843            uint32_t n_unused = 0;
2844
2845            for (const auto & t : token_to_id) {
2846                auto & attr = id_to_token[t.second].attr;
2847
2848                if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
2849                    continue;
2850                }
2851
2852                if ((attr & LLAMA_TOKEN_ATTR_UNUSED) == 0) {
2853                    if (strstr(t.first.c_str(), "unused") != NULL) {
2854                        attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_UNUSED);
2855                    }
2856                }
2857
2858                if (attr & LLAMA_TOKEN_ATTR_UNUSED) {
2859                    n_unused++;
2860                }
2861            }
2862
2863            LLAMA_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
2869        special_eog_ids.clear();
2870
2871        if (special_fim_pad_id != LLAMA_TOKEN_NULL && special_eog_ids.count(special_fim_pad_id) == 0) {
2872            special_eog_ids.insert(special_fim_pad_id);
2873        }
2874
2875        if (special_fim_rep_id != LLAMA_TOKEN_NULL && special_eog_ids.count(special_fim_rep_id) == 0) {
2876            special_eog_ids.insert(special_fim_rep_id);
2877        }
2878
2879        if (special_fim_sep_id != LLAMA_TOKEN_NULL && special_eog_ids.count(special_fim_sep_id) == 0) {
2880            special_eog_ids.insert(special_fim_sep_id);
2881        }
2882
2883        for (const auto & t : token_to_id) {
2884            auto & attr = id_to_token[t.second].attr;
2885
2886            if (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               ) {
2910                special_eog_ids.insert(t.second);
2911                if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
2912                    LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
2913                            __func__, t.second, t.first.c_str());
2914                    attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL);
2915                }
2916            } else {
2917                if (attr & LLAMA_TOKEN_ATTR_CONTROL && !(attr & LLAMA_TOKEN_ATTR_UNUSED)) {
2918                    // token is control, but not marked as EOG -> print a debug log
2919                    if (special_eog_ids.count(t.second) == 0) {
2920                        LLAMA_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
2928        for (const auto & t : token_to_id) {
2929            auto & attr = id_to_token[t.second].attr;
2930
2931            if (t.first == "<|channel|>" || t.first == "<|message|>" || t.first == "<|start|>" || t.first == "<|constrain|>") {
2932                LLAMA_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
2935                attr = LLAMA_TOKEN_ATTR_USER_DEFINED;
2936            }
2937        }
2938
2939        // sanity checks
2940        if (special_eos_id != LLAMA_TOKEN_NULL && special_eog_ids.count(special_eos_id) == 0) {
2941            special_eog_ids.insert(special_eos_id);
2942            LLAMA_LOG_WARN("%s: special_eos_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
2943        }
2944
2945        if (special_eot_id != LLAMA_TOKEN_NULL && special_eog_ids.count(special_eot_id) == 0) {
2946            special_eog_ids.insert(special_eot_id);
2947            LLAMA_LOG_WARN("%s: special_eot_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
2948        }
2949
2950        if (special_eom_id != LLAMA_TOKEN_NULL && special_eog_ids.count(special_eom_id) == 0) {
2951            special_eog_ids.insert(special_eom_id);
2952            LLAMA_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        {
2959            bool has_return = false;
2960            bool has_call   = false;
2961            bool has_end    = false;
2962            bool has_flush  = false;
2963
2964            llama_token end_id = LLAMA_TOKEN_NULL;
2965
2966            LLAMA_LOG_INFO("%s: printing all EOG tokens:\n", __func__);
2967            for (auto tid : special_eog_ids) {
2968                if (tid < 0 || tid >= (llama_token) id_to_token.size()) {
2969                    LLAMA_LOG_WARN("%s: EOG token id %d is out of range (vocab size %zu), skipping\n",
2970                            __func__, tid, id_to_token.size());
2971                    continue;
2972                }
2973                auto & text = id_to_token[tid].text;
2974
2975                LLAMA_LOG_INFO("%s:   - %d ('%s')\n", __func__, tid, text.c_str());
2976
2977                if (text == "<|return|>") {
2978                    has_return = true;
2979                } else if (text == "<|call|>" || text == "<|calls|>") {
2980                    has_call = true;
2981                } else if (text == "<|flush|>") {
2982                    has_flush = true;
2983                } else if (text == "<|end|>") {
2984                    has_end = true;
2985                    end_id = tid;
2986                }
2987            }
2988
2989            if ((has_return && has_call && has_end) || (has_call && has_flush && has_end)) {
2990                special_eog_ids.erase(end_id);
2991
2992                auto & attr = id_to_token[end_id].attr;
2993                attr = LLAMA_TOKEN_ATTR_USER_DEFINED;
2994
2995                LLAMA_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        {
3001            bool has_tool_response = false;
3002            bool has_s = false;
3003
3004            llama_token s_id = LLAMA_TOKEN_NULL;
3005
3006            for (auto tid : special_eog_ids) {
3007                if (tid < 0 || tid >= (llama_token) id_to_token.size()) {
3008                    continue;
3009                }
3010                const auto & text = id_to_token[tid].text;
3011                if (text == "<|tool_response>") {
3012                    has_tool_response = true;
3013                } else if (text == "</s>") {
3014                    has_s = true;
3015                    s_id = tid;
3016                }
3017            }
3018
3019            if (has_tool_response && has_s) {
3020                special_eog_ids.erase(s_id);
3021
3022                auto & attr = id_to_token[s_id].attr;
3023                attr = LLAMA_TOKEN_ATTR_NORMAL;
3024
3025                LLAMA_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    {
3032        for (llama_token id = 0; id < (llama_token) n_tokens; ++id) {
3033            if (id_to_token[id].attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED | LLAMA_TOKEN_ATTR_UNKNOWN)) {
3034                cache_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) {
3040                return id_to_token[a].text.size() > id_to_token[b].text.size();
3041            }
3042        );
3043
3044        LLAMA_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    {
3049        size_t size_cache = 0;
3050
3051        std::vector<std::string> cache(n_tokens);
3052
3053        for (uint32_t id = 0; id < n_tokens; ++id) {
3054            cache[id] = token_to_piece_for_cache(id, true);
3055
3056            size_cache += cache[id].size();
3057        }
3058
3059        std::swap(cache_token_to_piece, cache);
3060
3061        LLAMA_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    {
3069        auto _contains_any = [] (const std::string & str, const std::vector<std::string_view> & substrs) -> bool {
3070            for (const auto & substr : substrs) {
3071                if (str.find(substr) != std::string::npos) {
3072                    return true;
3073                }
3074            }
3075            return false;
3076        };
3077
3078        auto _set_tokenid_attr = [&] (const llama_token id, llama_token_attr attr, bool value) {
3079            uint32_t current = id_to_token.at(id).attr;
3080            current = value ? (current | attr) : (current & ~attr);
3081            id_to_token[id].attr = (llama_token_attr) current;
3082        };
3083
3084        auto _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
3092        ml.get_key(LLM_KV_GENERAL_NAME,  model_name,    false);
3093        ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
3094        ml.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) {
3099                return std::tolower(x);
3100            }
3101        );
3102
3103        // set attributes by model/tokenizer/architecture name
3104        if (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           ) {
3108            if (token_to_id.count("<mask>") == 0) {
3109                LLAMA_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"})) {
3114            for (auto id : cache_special_tokens) {
3115                _set_tokenid_attr(id, LLAMA_TOKEN_ATTR_RSTRIP, true);
3116            }
3117            for (const auto * token : {"</s>"}) {
3118                _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, true);
3119            }
3120            for (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"})) {
3124            if (token_to_id.count("[MASK]") == 0 ) {
3125                LLAMA_LOG_WARN("%s: Mask token missing in vocab!\n", __func__);
3126            }
3127            else {
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 {
3135    return type;
3136}
3137
3138std::string llama_vocab::impl::type_name() const{
3139    switch (type) {
3140        case LLAMA_VOCAB_TYPE_NONE:   return "no vocab";
3141        case LLAMA_VOCAB_TYPE_SPM:    return "SPM";
3142        case LLAMA_VOCAB_TYPE_BPE:    return "BPE";
3143        case LLAMA_VOCAB_TYPE_WPM:    return "WPM";
3144        case LLAMA_VOCAB_TYPE_UGM:    return "UGM";
3145        case LLAMA_VOCAB_TYPE_RWKV:   return "RWKV";
3146        case LLAMA_VOCAB_TYPE_PLAMO2: return "PLaMo2";
3147        case LLAMA_VOCAB_TYPE_TEST:   return "TEST";
3148        default:                      return "unknown";
3149    }
3150}
3151
3152bool llama_vocab::impl::is_normal(llama_token id) const {
3153    GGML_ASSERT(type != LLAMA_VOCAB_TYPE_NONE);
3154    return id_to_token[id].attr & LLAMA_TOKEN_ATTR_NORMAL;
3155}
3156
3157bool llama_vocab::impl::is_unknown(llama_token id) const {
3158    GGML_ASSERT(type != LLAMA_VOCAB_TYPE_NONE);
3159    return id_to_token[id].attr & LLAMA_TOKEN_ATTR_UNKNOWN;
3160}
3161
3162bool llama_vocab::impl::is_control(llama_token id) const {
3163    GGML_ASSERT(type != LLAMA_VOCAB_TYPE_NONE);
3164    return id_to_token[id].attr & LLAMA_TOKEN_ATTR_CONTROL;
3165}
3166
3167bool llama_vocab::impl::is_byte(llama_token id) const {
3168    GGML_ASSERT(type != LLAMA_VOCAB_TYPE_NONE);
3169    return id_to_token[id].attr & LLAMA_TOKEN_ATTR_BYTE;
3170}
3171
3172bool llama_vocab::impl::is_user_defined(llama_token id) const {
3173    GGML_ASSERT(type != LLAMA_VOCAB_TYPE_NONE);
3174    return id_to_token[id].attr & LLAMA_TOKEN_ATTR_USER_DEFINED;
3175}
3176
3177bool llama_vocab::impl::is_unused(llama_token id) const {
3178    GGML_ASSERT(type != LLAMA_VOCAB_TYPE_NONE);
3179    return id_to_token[id].attr & LLAMA_TOKEN_ATTR_UNUSED;
3180}
3181
3182bool llama_vocab::impl::is_eog(llama_token id) const {
3183    return id != LLAMA_TOKEN_NULL && special_eog_ids.count(id) > 0;
3184}
3185
3186uint8_t llama_vocab::impl::token_to_byte(llama_token id) const {
3187    GGML_ASSERT(get_type() != LLAMA_VOCAB_TYPE_NONE);
3188    GGML_ASSERT(is_byte(id));
3189    const auto & token_data = id_to_token.at(id);
3190    switch (get_type()) {
3191        case LLAMA_VOCAB_TYPE_SPM:
3192        case LLAMA_VOCAB_TYPE_UGM: {
3193            auto buf = token_data.text.substr(3, 2);
3194            return strtol(buf.c_str(), NULL, 16);
3195        }
3196        case LLAMA_VOCAB_TYPE_BPE: {
3197            // Gemma4 uses BPE with SPM-style byte fallback tokens (<0xXX>)
3198            auto buf = token_data.text.substr(3, 2);
3199            return strtol(buf.c_str(), NULL, 16);
3200        }
3201        case LLAMA_VOCAB_TYPE_WPM: {
3202            GGML_ABORT("fatal error");
3203        }
3204        default:
3205            GGML_ABORT("fatal error");
3206    }
3207}
3208
3209llama_token_attr llama_vocab::impl::token_get_attr(llama_token id) const {
3210    GGML_ASSERT(type != LLAMA_VOCAB_TYPE_NONE);
3211    return id_to_token.at(id).attr;
3212}
3213
3214void llama_vocab::impl::init_tokenizer(enum llama_vocab_type type) {
3215    LLAMA_LOG_DEBUG("%s: initializing tokenizer for type %d\n", __func__, type);
3216
3217    switch (type) {
3218        case LLAMA_VOCAB_TYPE_SPM:
3219            tokenizer = std::make_unique<llm_tokenizer_spm>(vocab);
3220            break;
3221        case LLAMA_VOCAB_TYPE_BPE:
3222            tokenizer = std::make_unique<llm_tokenizer_bpe>(vocab);
3223            break;
3224        case LLAMA_VOCAB_TYPE_WPM:
3225            tokenizer = std::make_unique<llm_tokenizer_wpm>(vocab);
3226            break;
3227        case LLAMA_VOCAB_TYPE_UGM:
3228            tokenizer = std::make_unique<llm_tokenizer_ugm>(vocab, precompiled_charsmap);
3229            break;
3230        case LLAMA_VOCAB_TYPE_RWKV:
3231            tokenizer = std::make_unique<llm_tokenizer_rwkv>(vocab);
3232            break;
3233        case LLAMA_VOCAB_TYPE_PLAMO2:
3234            tokenizer = std::make_unique<llm_tokenizer_plamo2>(vocab);
3235            break;
3236        case LLAMA_VOCAB_TYPE_TEST:
3237            tokenizer = std::make_unique<llm_tokenizer>();
3238            break;
3239        default:
3240            GGML_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
3252    for (const llama_token special_id : cache_special_tokens) {
3253        const auto & data = vocab.get_token_data(special_id);
3254        const auto & text = data.text;
3255
3256        if (!parse_special && (data.attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_UNKNOWN))) {
3257            // Ignore control and unknown tokens when parse_special == false
3258            continue;
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();
3266        while (it != buffer.end()) {
3267            auto & fragment = (*it);
3268
3269            // if a fragment is text ( not yet processed )
3270            if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
3271                const auto & raw_text = fragment.raw_text;
3272
3273                auto raw_text_base_offset = fragment.offset;
3274                auto raw_text_base_length = fragment.length;
3275
3276                // loop over the text
3277                while (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
3282                    auto 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
3285                    if (match == std::string::npos) break;
3286
3287#ifdef PRETOKENIZERDEBUG
3288                    LLAMA_LOG_WARN("FF: (%ld %ld %ld) '%s'\n", raw_text->length(), raw_text_base_offset, raw_text_base_length, raw_text->substr(raw_text_base_offset, raw_text_base_length).c_str());
3289#endif
3290                    auto 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
3294                    if (match > raw_text_base_offset) {
3295                        // left
3296                        const int64_t left_reminder_offset = raw_text_base_offset + 0;
3297                        int64_t left_reminder_length = match - raw_text_base_offset;
3298
3299                        if (data.attr & LLAMA_TOKEN_ATTR_LSTRIP) {
3300                            while (left_reminder_length > 0 && isspace(raw_text[left_reminder_offset + left_reminder_length - 1])) {
3301                                left_reminder_length--;
3302                            }
3303                        }
3304
3305                        if (left_reminder_length > 0) {
3306                            buffer.emplace_after(it, raw_text, left_reminder_offset, left_reminder_length);
3307                            it++;
3308                        }
3309
3310#ifdef PRETOKENIZERDEBUG
3311                        LLAMA_LOG_WARN("FL: (%ld %ld) '%s'\n", left_reminder_offset, left_reminder_length, raw_text->substr(left_reminder_offset, left_reminder_length).c_str());
3312#endif
3313                    }
3314
3315                    // special token
3316                    buffer.emplace_after(it, special_id);
3317                    it++;
3318
3319                    // right
3320                    if (match + text.length() < raw_text_base_offset + raw_text_base_length) {
3321                        int64_t right_reminder_offset = match + text.length();
3322                        int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + text.length());
3323
3324                        if (data.attr & LLAMA_TOKEN_ATTR_RSTRIP) {
3325                            while (right_reminder_length > 0 && isspace(raw_text[right_reminder_offset])) {
3326                                right_reminder_offset++;
3327                                right_reminder_length--;
3328                            }
3329                        }
3330
3331                        if (right_reminder_length > 0) {
3332                            buffer.emplace_after(it, raw_text, right_reminder_offset, right_reminder_length);
3333                            it++;
3334                        }
3335
3336#ifdef PRETOKENIZERDEBUG
3337                        LLAMA_LOG_WARN("FR: (%ld %ld) '%s'\n", right_reminder_offset, right_reminder_length, raw_text->substr(right_reminder_offset, right_reminder_length).c_str());
3338#endif
3339
3340                        if (source == 0) {
3341                            buffer.erase_after(buffer.before_begin());
3342                        } else {
3343                            buffer.erase_after(std::next(buffer.begin(), (source - 1)));
3344                        }
3345
3346                        // repeat for the right side
3347                        raw_text_base_offset = right_reminder_offset;
3348                        raw_text_base_length = right_reminder_length;
3349
3350#ifdef PRETOKENIZERDEBUG
3351                        LLAMA_LOG_WARN("RR: (%ld %ld) '%s'\n", raw_text_base_offset, raw_text_base_length, raw_text->substr(raw_text_base_offset, raw_text_base_length).c_str());
3352#endif
3353                    } else {
3354                        if (source == 0) {
3355                            buffer.erase_after(buffer.before_begin());
3356                        } else {
3357                            buffer.erase_after(std::next(buffer.begin(), (source - 1)));
3358                        }
3359                        break;
3360                    }
3361                }
3362            }
3363            it++;
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;
3371    piece.resize(piece.capacity());  // using string internal cache
3372    const int n_chars = vocab.token_to_piece(token, &piece[0], piece.size(), 0, special);
3373    if (n_chars < 0) {
3374        piece.resize(-n_chars);
3375        int check = vocab.token_to_piece(token, &piece[0], piece.size(), 0, special);
3376        GGML_ASSERT(check == -n_chars);
3377    }
3378    else {
3379        piece.resize(n_chars);
3380    }
3381
3382    return piece;
3383}
3384
3385static void llama_escape_whitespace(std::string & text) {
3386    replace_all(text, " ", "\xe2\x96\x81");
3387}
3388
3389static void llama_unescape_whitespace(std::string & word) {
3390    replace_all(word, "\xe2\x96\x81", " ");
3391}
3392
3393static std::string llama_decode_text(const std::string & text) {
3394    std::string decoded_text;
3395
3396    const auto cpts = unicode_cpts_from_utf8(text);
3397    for (const auto cpt : cpts) {
3398        const auto utf8 = unicode_cpt_to_utf8(cpt);
3399        try {
3400            decoded_text += unicode_utf8_to_byte(utf8);
3401        } catch (const std::out_of_range & /*e*/) {
3402            decoded_text += "[UNK_BYTE_0x";
3403            for (const auto c : utf8) {
3404                decoded_text += format("%02x", (uint8_t) c);
3405            }
3406            decoded_text += text + "]";
3407        }
3408    }
3409
3410    return decoded_text;
3411}
3412
3413std::vector<llama_token> llama_vocab::impl::tokenize(
3414        const std::string & raw_text,
3415        bool add_special,
3416        bool parse_special) const {
3417    GGML_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
3422    if (!raw_text.empty()) {
3423        fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
3424        tokenizer_st_partition(fragment_buffer, parse_special);
3425    }
3426
3427    switch (get_type()) {
3428        case 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
3435                bool is_prev_special = true;  // prefix with space if first token
3436
3437                if (add_special && add_bos) {
3438                    GGML_ASSERT(special_bos_id != LLAMA_TOKEN_NULL);
3439                    output.push_back(special_bos_id);
3440                    is_prev_special = true;
3441                }
3442
3443                for (const auto & fragment : fragment_buffer) {
3444                    if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
3445                        std::string text;
3446
3447                        // prefix with space if previous is special
3448                        if (add_space_prefix && is_prev_special) {
3449                            text = ' ';
3450                        }
3451
3452                        text += fragment.raw_text.substr(fragment.offset, fragment.length);
3453
3454#ifdef PRETOKENIZERDEBUG
3455                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
3456#endif
3457                        llama_escape_whitespace(text);
3458                        llm_tokenizer_spm_session session(vocab);
3459                        session.tokenize(text, output);
3460                        is_prev_special = false;
3461                    } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
3462                        output.push_back(fragment.token);
3463                        is_prev_special = true;
3464                    }
3465                }
3466
3467                if (add_special && add_bos && output.size() >= 2 && output[1] == special_bos_id) {
3468                    LLAMA_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
3474                if (add_special && add_eos) {
3475                    GGML_ASSERT(special_eos_id != LLAMA_TOKEN_NULL);
3476                    output.push_back(special_eos_id);
3477                }
3478            } break;
3479        case 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
3483                const llm_tokenizer_bpe * tok_bpe = static_cast<const llm_tokenizer_bpe *>(tokenizer.get());
3484
3485                std::unique_ptr<llm_tokenizer_bpe_session> session;
3486                if (vocab.get_tokenizer_model() == "hybriddna") {
3487                    session = std::make_unique<llm_tokenizer_hybriddna_session>(vocab, *tok_bpe);
3488                } else if (vocab.get_tokenizer_model() == "whitespace") {
3489                    session = std::make_unique<llm_tokenizer_whitespace_session>(vocab, *tok_bpe);
3490                } else {
3491                    session = std::make_unique<llm_tokenizer_bpe_session>(vocab, *tok_bpe);
3492                }
3493
3494                if (add_special) {
3495                    session->append_bos(output);
3496                }
3497                for (const auto & fragment : fragment_buffer) {
3498                    if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
3499                        std::string text = fragment.raw_text.substr(fragment.offset, fragment.length);
3500
3501                        if (escape_whitespaces) {
3502                            llama_escape_whitespace(text);
3503                        }
3504
3505#ifdef PRETOKENIZERDEBUG
3506                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
3507#endif
3508                        session->tokenize(text, output);
3509                    } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
3510                        session->append(fragment.token, output);
3511                    }
3512                }
3513
3514                if (add_special) {
3515                    session->append_eos(output);
3516                    session->check_double_bos_eos(output);
3517                }
3518            } break;
3519        case LLAMA_VOCAB_TYPE_WPM:
3520            {
3521                if (add_special) {
3522                    GGML_ASSERT(special_bos_id != LLAMA_TOKEN_NULL);
3523                    output.push_back(special_bos_id);
3524                }
3525
3526                llm_tokenizer_wpm_session session(vocab);
3527
3528                for (const auto & fragment : fragment_buffer) {
3529                    if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
3530                        std::string text = fragment.raw_text.substr(fragment.offset, fragment.length);
3531
3532#ifdef PRETOKENIZERDEBUG
3533                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
3534#endif
3535                        session.tokenize(text, output);
3536                    } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
3537                        output.push_back(fragment.token);
3538                    }
3539                }
3540
3541                if (add_special) {
3542                    GGML_ASSERT(special_sep_id != LLAMA_TOKEN_NULL);
3543                    output.push_back(special_sep_id);
3544                }
3545            } break;
3546        case LLAMA_VOCAB_TYPE_UGM:
3547            {
3548                if (add_special && add_bos) {
3549                    GGML_ASSERT(special_bos_id != LLAMA_TOKEN_NULL);
3550                    output.push_back(special_bos_id);
3551                }
3552                llm_tokenizer_ugm_session session(vocab, *static_cast<const llm_tokenizer_ugm *>(tokenizer.get()));
3553
3554                for (const auto & fragment : fragment_buffer) {
3555                    if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
3556                        std::string text = fragment.raw_text.substr(fragment.offset, fragment.length);
3557#ifdef PRETOKENIZERDEBUG
3558                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
3559#endif
3560                        session.tokenize(text, output);
3561                    } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
3562                        output.push_back(fragment.token);
3563                    }
3564                }
3565
3566                if (add_special && add_bos && output.size() >= 2 && output[1] == special_bos_id) {
3567                    LLAMA_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
3573                if (add_special && add_eos) {
3574                    GGML_ASSERT(special_eos_id != LLAMA_TOKEN_NULL);
3575                    output.push_back(special_eos_id);
3576                }
3577            } break;
3578        case LLAMA_VOCAB_TYPE_RWKV:
3579            {
3580                llm_tokenizer_rwkv_session session(vocab, *static_cast<const llm_tokenizer_rwkv *>(tokenizer.get()));
3581                for (const auto & fragment : fragment_buffer) {
3582                    if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
3583                        std::string text = fragment.raw_text.substr(fragment.offset, fragment.length);
3584
3585#ifdef PRETOKENIZERDEBUG
3586                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
3587#endif
3588
3589                        session.tokenize(text, output);
3590                    } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
3591                        output.push_back(fragment.token);
3592                    }
3593                }
3594            } break;
3595        case LLAMA_VOCAB_TYPE_PLAMO2:
3596            {
3597                llm_tokenizer_plamo2_session session(*static_cast<const llm_tokenizer_plamo2 *>(tokenizer.get()));
3598                for (const auto & fragment : fragment_buffer) {
3599                    if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
3600                        std::string text = fragment.raw_text.substr(fragment.offset, fragment.length);
3601
3602#ifdef PRETOKENIZERDEBUG
3603                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
3604#endif
3605
3606                        session.tokenize(text, output);
3607                    } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
3608                        output.push_back(fragment.token);
3609                    }
3610                }
3611            } break;
3612        case LLAMA_VOCAB_TYPE_TEST:
3613            {
3614                const uint32_t n_vocab = vocab.n_tokens();
3615                constexpr size_t chunk_size = 5;
3616
3617                // reserve output to avoid repeated reallocations
3618                size_t n_tokens = 0;
3619                for (const auto & fragment : fragment_buffer) {
3620                    if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
3621                        n_tokens += (fragment.length + chunk_size - 1) / chunk_size;
3622                    } else {
3623                        ++n_tokens;
3624                    }
3625                }
3626                output.reserve(output.size() + n_tokens);
3627
3628                for (const auto & fragment : fragment_buffer) {
3629                    if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
3630                        const auto & text = fragment.raw_text;
3631                        const size_t begin = fragment.offset;
3632                        const size_t end   = begin + fragment.length;
3633                        size_t pos = begin;
3634                        while (pos < end) {
3635                            const size_t n = std::min(chunk_size, end - pos);
3636                            uint64_t hash = 0;
3637                            for (size_t i = 0; i < n; ++i) {
3638                                hash = hash*31 + (uint8_t) text[pos + i];
3639                            }
3640                            output.push_back((llama_token)(hash % n_vocab));
3641                            pos += n;
3642                        }
3643                    } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
3644                        output.push_back(fragment.token);
3645                    }
3646                }
3647            } break;
3648        case LLAMA_VOCAB_TYPE_NONE:
3649            GGML_ABORT("fatal error");
3650    }
3651
3652    return 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
3657    static const int attr_special = LLAMA_TOKEN_ATTR_UNKNOWN | LLAMA_TOKEN_ATTR_CONTROL;
3658    const llama_token_attr attr = token_get_attr(token);
3659    if (!special && (attr & attr_special)) {
3660        return 0;
3661    }
3662
3663    // copy piece chars to output text buffer
3664    // skip up to 'lstrip' leading spaces before copying
3665    auto _try_copy = [=] (const char * token, size_t size) -> int32_t {
3666        if (size >= static_cast<size_t>(std::numeric_limits<int32_t>::max())) {
3667            GGML_ABORT("invalid token size: %zu exceeds int32_t limit", size);
3668        }
3669
3670        for (int32_t i = 0; i < lstrip && size && *token == ' '; ++i) {
3671            token++;
3672            size--;
3673        }
3674        if (length < (int32_t)size) {
3675            return -(int32_t) size;
3676        }
3677        memcpy(buf, token, size);
3678        return (int32_t) size;
3679    };
3680
3681    // if we have a cache - use it
3682    {
3683        const auto & cache = cache_token_to_piece;
3684
3685        if (!cache.empty()) {
3686            const auto & result = cache.at(token);
3687            return _try_copy(result.data(), result.size());
3688        }
3689    }
3690
3691    if (0 <= token && token < (int32_t) id_to_token.size()) {
3692        const std::string & token_text = id_to_token[token].text;
3693        switch (get_type()) {
3694            case LLAMA_VOCAB_TYPE_WPM:
3695            case LLAMA_VOCAB_TYPE_SPM:
3696            case LLAMA_VOCAB_TYPE_UGM: {
3697                // NOTE: we accept all unsupported token types,
3698                // suppressing them like CONTROL tokens.
3699                if (attr & (attr_special | LLAMA_TOKEN_ATTR_USER_DEFINED)) {
3700                    return _try_copy(token_text.data(), token_text.size());
3701                }
3702                if (attr & LLAMA_TOKEN_ATTR_NORMAL) {
3703                    std::string result = token_text;
3704                    llama_unescape_whitespace(result);
3705                    return _try_copy(result.data(), result.size());
3706                }
3707                if (attr & LLAMA_TOKEN_ATTR_BYTE) {
3708                    char byte = (char) token_to_byte(token);
3709                    return _try_copy((char*) &byte, 1);
3710                }
3711                break;
3712            }
3713            case LLAMA_VOCAB_TYPE_BPE: {
3714                // NOTE: we accept all unsupported token types,
3715                // suppressing them like CONTROL tokens.
3716                if (attr & (attr_special | LLAMA_TOKEN_ATTR_USER_DEFINED)) {
3717                    return _try_copy(token_text.data(), token_text.size());
3718                }
3719                if (attr & LLAMA_TOKEN_ATTR_NORMAL) {
3720                    if (escape_whitespaces) {
3721                        // SPM-style BPE: tokens contain ▁ for spaces
3722                        std::string result = token_text;
3723                        llama_unescape_whitespace(result);
3724                        return _try_copy(result.data(), result.size());
3725                    }
3726                    std::string result = llama_decode_text(token_text);
3727                    return _try_copy(result.data(), result.size());
3728                }
3729                if (attr & LLAMA_TOKEN_ATTR_BYTE) {
3730                    char byte = (char) token_to_byte(token);
3731                    return _try_copy((char*) &byte, 1);
3732                }
3733                break;
3734            }
3735            case 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
3739                if (result.size() > (size_t)length) {
3740                    return -(int)result.size();
3741                }
3742
3743                memcpy(buf, result.data(), result.size());
3744                return (int)result.size();
3745            }
3746            case LLAMA_VOCAB_TYPE_TEST: {
3747                // tokens -> text: simply stringify the token id in hex
3748                std::string result = format("%x", token);
3749                return _try_copy(result.data(), result.size());
3750            }
3751            case LLAMA_VOCAB_TYPE_PLAMO2: {
3752                // PLaMo-2 uses similar token handling as BPE/SPM
3753                if (vocab.is_byte(token)) {
3754                    // Handle byte tokens like <0xXX>
3755                    if (token_text.length() == 6 && token_text.substr(0, 3) == "<0x" && token_text.back() == '>') {
3756                        std::string hex_str = token_text.substr(3, 2);
3757                        if (std::isxdigit(static_cast<unsigned char>(hex_str[0])) && std::isxdigit(static_cast<unsigned char>(hex_str[1]))) {
3758                            int hex_val = std::stoi(hex_str, nullptr, 16);
3759                            if (length < 1) {
3760                                return -1;
3761                            }
3762                            buf[0] = static_cast<char>(hex_val);
3763                            return 1;
3764                        }
3765                    }
3766                }
3767
3768                // Normal token - just copy the text
3769                std::string result = token_text;
3770                return _try_copy(result.data(), result.size());
3771            }
3772            default:
3773                GGML_ABORT("fatal error");
3774        }
3775    }
3776
3777    return 0;
3778}
3779
3780const std::string & llama_vocab::impl::token_to_piece(llama_token token) const {
3781    return cache_token_to_piece.at(token);
3782}
3783
3784int32_t llama_vocab::impl::detokenize(
3785               const llama_token * tokens,
3786                         int32_t   n_tokens,
3787                            char * text,
3788                         int32_t   text_len_max,
3789                            bool   remove_special,
3790                            bool   unparse_special) const {
3791    if (type == LLAMA_VOCAB_TYPE_NONE) {
3792        return 0;
3793    }
3794
3795    GGML_ASSERT(tokenizer && "Tokenizer not initialized. Call llama_vocab::init_tokenizer() first.");
3796
3797    int32_t avail = text_len_max;
3798    int32_t total = 0;
3799
3800    // remove the leading space
3801    bool remove_space = add_space_prefix;
3802
3803    if (remove_special && add_bos) {
3804        if (n_tokens > 0 && tokens[0] == special_bos_id) {
3805            remove_space = false;
3806            n_tokens--;
3807            tokens++;
3808        }
3809    }
3810
3811    if (remove_special && add_eos) {
3812        if (n_tokens > 0 && tokens[n_tokens - 1] == special_eos_id) {
3813            n_tokens--;
3814        }
3815    }
3816
3817    for (int32_t i = 0; i < n_tokens; ++i) {
3818        GGML_ASSERT(avail >= 0);
3819        int32_t n_chars = token_to_piece(tokens[i], text, avail, remove_space, unparse_special);
3820        remove_space = false;
3821        if (n_chars < 0) {
3822            avail = 0;
3823            total -= n_chars;
3824        } else if (n_chars > 0) {
3825            avail -= n_chars;
3826            text  += n_chars;
3827            total += n_chars;
3828        }
3829    }
3830
3831    if (total > text_len_max) {
3832        return -total;
3833    }
3834
3835    if (clean_spaces) {
3836        text -= total;  // restart text
3837
3838        // first pass: characters ?!.,  //TODO: where do these characters come from?
3839        const int32_t total1 = total;
3840        total = total ? 1 : 0;
3841        for (int32_t i = 1; i < total1; ++i) {
3842            const char x = text[i];
3843            if (text[i - 1] == ' ') {
3844                if (x == '?' || x == '!' || x == '.' || x == ',') {  // " ?", " !", " .", " ,"
3845                    total--;  // remove space
3846                }
3847            }
3848            text[total++] = x;
3849        }
3850
3851        // second pass: strip single apostrophe between spaces
3852        const int32_t total2 = total;
3853        total = total ? 1 : 0;
3854        for (int32_t i = 1; i < total2; ++i) {
3855            const char x = text[i];
3856            if (x == '\'' && i + 1 < total2 && text[i - 1] == ' ' && text[i + 1] == ' ') {  // " ' "
3857                total--;           // remove prev space
3858                text[++i] = '\0';  // remove next space
3859            }
3860            text[total++] = x;
3861        }
3862
3863        // third pass: apostrophe contractions  //NOTE: this makes sense?
3864        const int32_t total3 = total;
3865        total = total ? 1 : 0;
3866        for (int32_t i = 1; i < total3; ++i) {
3867            const char x = text[i];
3868            if (text[i - 1] == ' ') {
3869                if (x == '\'' && i + 1 < total3) {
3870                    const char x1 = text[i + 1];
3871                    if (x1 == 't' || x1 == 'd') {  // " 't", " 'd"
3872                        //total--;  // remove space
3873                    } else if (x1 == 's' || x1 == 'm') {  // " 's", " 'm"
3874                        total--;  // remove space
3875                    } else if (i + 2 < total3) {
3876                        const char x2 = text[i + 2];
3877                        if ((x1 == 'l' && x2 == 'l')) {  // " 'll"
3878                            //total--;  // remove space
3879                        } else if ((x1 == 'r' && x2 == 'e') || (x1 == 'v' && x2 == 'e')) {  // " 're", " 've"
3880                            total--;  // remove space
3881                        } else {
3882                            //total--;  // remove space
3883                        }
3884                    } else {
3885                        //total--;  // remove space
3886                    }
3887                }
3888            }
3889            text[total++] = x;
3890        }
3891    }
3892
3893    return total <= text_len_max ? total : -total;
3894}
3895
3896void llama_vocab::impl::print_info() const {
3897    LLAMA_LOG_INFO("%s: vocab type            = %s\n",     __func__, type_name().c_str());
3898    LLAMA_LOG_INFO("%s: n_vocab               = %u\n",     __func__, vocab.n_tokens());
3899    LLAMA_LOG_INFO("%s: n_merges              = %u\n",     __func__, (uint32_t) bpe_ranks.size());
3900
3901    // special tokens
3902    if (special_bos_id  != LLAMA_TOKEN_NULL)    { LLAMA_LOG_INFO( "%s: BOS token             = %d '%s'\n", __func__, special_bos_id,     id_to_token.at(special_bos_id).text.c_str() );  }
3903    if (special_eos_id  != LLAMA_TOKEN_NULL)    { LLAMA_LOG_INFO( "%s: EOS token             = %d '%s'\n", __func__, special_eos_id,     id_to_token.at(special_eos_id).text.c_str() );  }
3904    if (special_eot_id  != LLAMA_TOKEN_NULL)    { LLAMA_LOG_INFO( "%s: EOT token             = %d '%s'\n", __func__, special_eot_id,     id_to_token.at(special_eot_id).text.c_str() );  }
3905    if (special_eom_id  != LLAMA_TOKEN_NULL)    { LLAMA_LOG_INFO( "%s: EOM token             = %d '%s'\n", __func__, special_eom_id,     id_to_token.at(special_eom_id).text.c_str() );  }
3906    if (special_unk_id  != LLAMA_TOKEN_NULL)    { LLAMA_LOG_INFO( "%s: UNK token             = %d '%s'\n", __func__, special_unk_id,     id_to_token.at(special_unk_id).text.c_str() );  }
3907    if (special_sep_id  != LLAMA_TOKEN_NULL)    { LLAMA_LOG_INFO( "%s: SEP token             = %d '%s'\n", __func__, special_sep_id,     id_to_token.at(special_sep_id).text.c_str() );  }
3908    if (special_pad_id  != LLAMA_TOKEN_NULL)    { LLAMA_LOG_INFO( "%s: PAD token             = %d '%s'\n", __func__, special_pad_id,     id_to_token.at(special_pad_id).text.c_str() );  }
3909    if (special_mask_id != LLAMA_TOKEN_NULL)    { LLAMA_LOG_INFO( "%s: MASK token            = %d '%s'\n", __func__, special_mask_id,    id_to_token.at(special_mask_id).text.c_str() ); }
3910
3911    if (linefeed_id != LLAMA_TOKEN_NULL)        { LLAMA_LOG_INFO( "%s: LF token              = %d '%s'\n", __func__, linefeed_id,        id_to_token.at(linefeed_id).text.c_str() ); }
3912
3913    if (special_fim_pre_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM PRE token         = %d '%s'\n", __func__, special_fim_pre_id, id_to_token.at(special_fim_pre_id).text.c_str() ); }
3914    if (special_fim_suf_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM SUF token         = %d '%s'\n", __func__, special_fim_suf_id, id_to_token.at(special_fim_suf_id).text.c_str() ); }
3915    if (special_fim_mid_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM MID token         = %d '%s'\n", __func__, special_fim_mid_id, id_to_token.at(special_fim_mid_id).text.c_str() ); }
3916    if (special_fim_pad_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM PAD token         = %d '%s'\n", __func__, special_fim_pad_id, id_to_token.at(special_fim_pad_id).text.c_str() ); }
3917    if (special_fim_rep_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM REP token         = %d '%s'\n", __func__, special_fim_rep_id, id_to_token.at(special_fim_rep_id).text.c_str() ); }
3918    if (special_fim_sep_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM SEP token         = %d '%s'\n", __func__, special_fim_sep_id, id_to_token.at(special_fim_sep_id).text.c_str() ); }
3919
3920    for (const auto & id : special_eog_ids) {
3921        LLAMA_LOG_INFO( "%s: EOG token             = %d '%s'\n", __func__, id, id_to_token.at(id).text.c_str() );
3922    }
3923
3924    LLAMA_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) {
3933    pimpl->load(ml, kv);
3934}
3935
3936std::string llama_vocab::get_tokenizer_model() const {
3937    return pimpl->tokenizer_model;
3938}
3939
3940std::string llama_vocab::get_tokenizer_pre() const {
3941    return pimpl->tokenizer_pre;
3942}
3943
3944enum llama_vocab_type llama_vocab::get_type() const {
3945    return pimpl->type;
3946}
3947
3948enum llama_vocab_pre_type llama_vocab::get_pre_type() const {
3949    return pimpl->pre_type;
3950}
3951
3952uint32_t llama_vocab::n_tokens() const {
3953    return (uint32_t) pimpl->id_to_token.size();
3954}
3955
3956uint32_t llama_vocab::n_token_types() const {
3957    return (uint32_t) pimpl->n_token_types;
3958}
3959
3960std::string llama_vocab::type_name() const{
3961    return pimpl->type_name();
3962}
3963
3964bool llama_vocab::is_normal(llama_token id) const {
3965    return pimpl->is_normal(id);
3966}
3967
3968bool llama_vocab::is_unknown(llama_token id) const {
3969    return pimpl->is_unknown(id);
3970}
3971
3972bool llama_vocab::is_control(llama_token id) const {
3973    return pimpl->is_control(id);
3974}
3975
3976bool llama_vocab::is_byte(llama_token id) const {
3977    return pimpl->is_byte(id);
3978}
3979
3980bool llama_vocab::is_user_defined(llama_token id) const {
3981    return pimpl->is_user_defined(id);
3982}
3983
3984bool llama_vocab::is_unused(llama_token id) const {
3985    return pimpl->is_unused(id);
3986}
3987
3988bool llama_vocab::is_eog(llama_token id) const {
3989    return pimpl->is_eog(id);
3990}
3991
3992uint8_t llama_vocab::token_to_byte(llama_token id) const {
3993    return pimpl->token_to_byte(id);
3994}
3995
3996llama_token llama_vocab::byte_to_token(uint8_t ch) const {
3997    GGML_ASSERT(get_type() != LLAMA_VOCAB_TYPE_NONE);
3998    static const char * hex = "0123456789ABCDEF";
3999    switch (get_type()) {
4000        case LLAMA_VOCAB_TYPE_SPM:
4001        case LLAMA_VOCAB_TYPE_UGM: {
4002            const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
4003            auto token = pimpl->token_to_id.find(buf);
4004            if (token != pimpl->token_to_id.end()) {
4005                return (*token).second;
4006            }
4007            // Try to fall back to just the byte as a string
4008            const char buf2[2] = { (char)ch, 0 };
4009            return pimpl->token_to_id.at(buf2);
4010        }
4011        case LLAMA_VOCAB_TYPE_WPM:
4012        case LLAMA_VOCAB_TYPE_BPE: {
4013            return pimpl->token_to_id.at(unicode_byte_to_utf8(ch));
4014        }
4015        case LLAMA_VOCAB_TYPE_PLAMO2: {
4016            // PLaMo-2 uses byte tokens in format <0xXX>
4017            char hex_str[8];
4018            snprintf(hex_str, sizeof(hex_str), "<0x%02X>", ch);
4019            return pimpl->token_to_id.at(hex_str);
4020        }
4021        case LLAMA_VOCAB_TYPE_TEST:
4022            // TEST tokens have no byte-level mapping
4023            return LLAMA_TOKEN_NULL;
4024        default:
4025            GGML_ABORT("fatal error");
4026    }
4027}
4028
4029llama_token llama_vocab::text_to_token(const std::string & text) const {
4030    GGML_ASSERT(pimpl->type != LLAMA_VOCAB_TYPE_NONE);
4031    auto it = pimpl->token_to_id.find(text);
4032    if (it != pimpl->token_to_id.end()) {
4033        return (*it).second;
4034    }
4035    return LLAMA_TOKEN_NULL;
4036}
4037
4038const llama_vocab::token_data & llama_vocab::get_token_data(llama_token id) const {
4039    GGML_ASSERT(pimpl->type != LLAMA_VOCAB_TYPE_NONE);
4040    return pimpl->id_to_token.at(id);
4041}
4042
4043const char * llama_vocab::token_get_text(llama_token id) const {
4044    GGML_ASSERT(pimpl->type != LLAMA_VOCAB_TYPE_NONE);
4045    return pimpl->id_to_token.at(id).text.c_str();
4046}
4047
4048float llama_vocab::token_get_score(llama_token id) const {
4049    GGML_ASSERT(pimpl->type != LLAMA_VOCAB_TYPE_NONE);
4050    return pimpl->id_to_token.at(id).score;
4051}
4052
4053llama_token_attr llama_vocab::token_get_attr(llama_token id) const {
4054    return pimpl->token_get_attr(id);
4055}
4056
4057llama_token llama_vocab::token_bos() const {
4058    return pimpl->special_bos_id;
4059}
4060
4061llama_token llama_vocab::token_eos() const {
4062    return pimpl->special_eos_id;
4063}
4064
4065llama_token llama_vocab::token_eot() const {
4066    return pimpl->special_eot_id;
4067}
4068
4069llama_token llama_vocab::token_eom() const {
4070    return pimpl->special_eom_id;
4071}
4072
4073llama_token llama_vocab::token_unk() const {
4074    return pimpl->special_unk_id;
4075}
4076
4077llama_token llama_vocab::token_sep() const {
4078    return pimpl->special_sep_id;
4079}
4080
4081llama_token llama_vocab::token_nl() const {
4082    return pimpl->linefeed_id;
4083}
4084
4085llama_token llama_vocab::token_pad() const {
4086    return pimpl->special_pad_id;
4087}
4088
4089llama_token llama_vocab::token_prefix() const {
4090    return pimpl->special_fim_pre_id;
4091}
4092
4093llama_token llama_vocab::token_middle() const {
4094    return pimpl->special_fim_mid_id;
4095}
4096
4097llama_token llama_vocab::token_suffix() const {
4098    return pimpl->special_fim_suf_id;
4099}
4100
4101llama_token llama_vocab::token_fim_pre() const {
4102    return pimpl->special_fim_pre_id;
4103}
4104
4105llama_token llama_vocab::token_fim_suf() const {
4106    return pimpl->special_fim_suf_id;
4107}
4108
4109llama_token llama_vocab::token_fim_mid() const {
4110    return pimpl->special_fim_mid_id;
4111}
4112
4113llama_token llama_vocab::token_fim_pad() const {
4114    return pimpl->special_fim_pad_id;
4115}
4116
4117llama_token llama_vocab::token_fim_rep() const {
4118    return pimpl->special_fim_rep_id;
4119}
4120
4121llama_token llama_vocab::token_fim_sep() const {
4122    return pimpl->special_fim_sep_id;
4123}
4124
4125llama_token llama_vocab::token_mask() const {
4126    return pimpl->special_mask_id;
4127}
4128
4129bool llama_vocab::get_add_space_prefix() const {
4130    return pimpl->add_space_prefix;
4131}
4132
4133bool llama_vocab::get_add_bos() const {
4134    return pimpl->add_bos;
4135}
4136
4137bool llama_vocab::get_add_eos() const {
4138    return pimpl->add_eos;
4139}
4140
4141bool llama_vocab::get_add_sep() const {
4142    return pimpl->add_sep;
4143}
4144
4145bool llama_vocab::get_ignore_merges() const {
4146    return pimpl->ignore_merges;
4147}
4148
4149bool llama_vocab::get_clean_spaces() const {
4150    return pimpl->clean_spaces;
4151}
4152
4153bool llama_vocab::get_remove_extra_whitespaces() const {
4154    return pimpl->remove_extra_whitespaces;
4155}
4156
4157bool llama_vocab::get_escape_whitespaces() const {
4158    return pimpl->escape_whitespaces;
4159}
4160
4161bool llama_vocab::get_treat_whitespace_as_suffix() const {
4162    return pimpl->treat_whitespace_as_suffix;
4163}
4164
4165const llama_vocab::normalizer_options & llama_vocab::get_normalizer_opts() const {
4166    return pimpl->normalizer_opts;
4167}
4168
4169const std::vector<llama_token> & llama_vocab::get_suppress_tokens() const {
4170    return pimpl->suppress_tokens;
4171}
4172
4173int llama_vocab::max_token_len() const {
4174    return pimpl->max_token_len;
4175}
4176
4177int llama_vocab::find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
4178    GGML_ASSERT(token_left.find(' ')   == std::string::npos);
4179    GGML_ASSERT(token_right.find(' ')  == std::string::npos);
4180
4181    auto it = pimpl->bpe_ranks.find(std::make_pair(token_left, token_right));
4182    if (it == pimpl->bpe_ranks.end()) {
4183        return -1;
4184    }
4185
4186    return it->second;
4187}
4188
4189std::vector<std::string> llama_vocab::get_bpe_merges() const {
4190    int max_rank = -1;
4191    for (const auto & pair : pimpl->bpe_ranks) {
4192        max_rank = std::max(max_rank, pair.second);
4193    }
4194    std::vector<std::string> result(max_rank + 1);
4195
4196    for (const auto & pair : pimpl->bpe_ranks) {
4197        result[pair.second] = pair.first.first + " " + pair.first.second;
4198    }
4199
4200    return result;
4201}
4202
4203std::vector<char> llama_vocab::get_precompiled_charsmap() const {
4204    return pimpl->precompiled_charsmap;
4205}
4206
4207int32_t llama_vocab::tokenize(
4208                  const char * text,
4209                     int32_t   text_len,
4210                 llama_token * tokens,
4211                     int32_t   n_tokens_max,
4212                        bool   add_special,
4213                        bool   parse_special) const {
4214    auto res = tokenize(std::string(text, text_len), add_special, parse_special);
4215    if (res.size() >= static_cast<size_t>(std::numeric_limits<int32_t>::max())) {
4216        LLAMA_LOG_ERROR("%s: tokenization result size %zu exceeds int32_t limit\n", __func__, res.size());
4217        return std::numeric_limits<int32_t>::min();
4218    }
4219
4220    if (n_tokens_max < (int) res.size()) {
4221        // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
4222        return -((int) res.size());
4223    }
4224
4225    for (size_t i = 0; i < res.size(); i++) {
4226        tokens[i] = res[i];
4227    }
4228
4229    return res.size();
4230}
4231
4232std::vector<llama_token> llama_vocab::tokenize(
4233        const std::string & raw_text,
4234        bool add_special,
4235        bool parse_special) const {
4236    return pimpl->tokenize(raw_text, add_special, parse_special);
4237}
4238
4239const std::string & llama_vocab::token_to_piece(llama_token token) const {
4240    return 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 {
4244    return pimpl->token_to_piece(token, buf, length, lstrip, special);
4245}
4246
4247int32_t llama_vocab::detokenize(
4248               const llama_token * tokens,
4249                         int32_t   n_tokens,
4250                            char * text,
4251                         int32_t   text_len_max,
4252                            bool   remove_special,
4253                            bool   unparse_special) const {
4254    return 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;
4259    text.resize(std::max(text.capacity(), tokens.size()));
4260    int32_t n_chars = detokenize(tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
4261    if (n_chars < 0) {
4262        text.resize(-n_chars);
4263        n_chars = detokenize(tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
4264        GGML_ASSERT(n_chars <= (int32_t)text.size());  // whitespace trimming is performed after per-token detokenization
4265    }
4266
4267    text.resize(n_chars);
4268
4269    // NOTE: the original tokenizer decodes bytes after collecting the pieces.
4270    return text;
4271}
4272
4273void llama_vocab::print_info() const {
4274    pimpl->print_info();
4275}
4276
4277//
4278// interface implementation
4279//
4280
4281int32_t llama_vocab_n_tokens(const struct llama_vocab * vocab) {
4282    return vocab->n_tokens();
4283}
4284
4285// deprecated
4286int32_t llama_n_vocab(const struct llama_vocab * vocab) {
4287    return llama_vocab_n_tokens(vocab);
4288}
4289
4290enum llama_vocab_type llama_vocab_type(const struct llama_vocab * vocab) {
4291    return vocab->get_type();
4292}
4293
4294const char * llama_vocab_get_text(const struct llama_vocab * vocab, llama_token token) {
4295    return vocab->token_get_text(token);
4296}
4297
4298float llama_vocab_get_score(const struct llama_vocab * vocab, llama_token token) {
4299    return vocab->token_get_score(token);
4300}
4301
4302enum llama_token_attr llama_vocab_get_attr(const struct llama_vocab * vocab, llama_token token) {
4303    return vocab->token_get_attr(token);
4304}
4305
4306bool llama_vocab_is_eog(const struct llama_vocab * vocab, llama_token token) {
4307    return vocab->is_eog(token);
4308}
4309
4310bool llama_vocab_is_control(const struct llama_vocab * vocab, llama_token token) {
4311    return vocab->is_control(token);
4312}
4313
4314llama_token llama_vocab_bos(const struct llama_vocab * vocab) {
4315    return vocab->token_bos();
4316}
4317
4318llama_token llama_vocab_eos(const struct llama_vocab * vocab) {
4319    return vocab->token_eos();
4320}
4321
4322llama_token llama_vocab_eot(const struct llama_vocab * vocab) {
4323    return vocab->token_eot();
4324}
4325
4326// deprecated
4327llama_token llama_vocab_cls(const struct llama_vocab * vocab) {
4328    return vocab->token_bos();
4329}
4330
4331llama_token llama_vocab_sep(const struct llama_vocab * vocab) {
4332    return vocab->token_sep();
4333}
4334
4335llama_token llama_vocab_nl (const struct llama_vocab * vocab) {
4336    return vocab->token_nl();
4337}
4338
4339llama_token llama_vocab_pad(const struct llama_vocab * vocab) {
4340    return vocab->token_pad();
4341}
4342
4343bool llama_vocab_get_add_bos(const struct llama_vocab * vocab) {
4344    return vocab->get_add_bos();
4345}
4346
4347bool llama_vocab_get_add_eos(const struct llama_vocab * vocab) {
4348    return vocab->get_add_eos();
4349}
4350
4351bool llama_vocab_get_add_sep(const struct llama_vocab * vocab) {
4352    return vocab->get_add_sep();
4353}
4354
4355const llama_token * llama_vocab_get_suppress_tokens(const struct llama_vocab * vocab, int32_t * n_suppress_tokens) {
4356    const std::vector<llama_token> & tokens = vocab->get_suppress_tokens();
4357    if (n_suppress_tokens) {
4358        *n_suppress_tokens = (int32_t) tokens.size();
4359    }
4360    return tokens.data();
4361}
4362
4363llama_token llama_vocab_fim_pre(const struct llama_vocab * vocab) {
4364    return vocab->token_fim_pre();
4365}
4366
4367llama_token llama_vocab_fim_suf(const struct llama_vocab * vocab) {
4368    return vocab->token_fim_suf();
4369}
4370
4371llama_token llama_vocab_fim_mid(const struct llama_vocab * vocab) {
4372    return vocab->token_fim_mid();
4373}
4374
4375llama_token llama_vocab_fim_pad(const struct llama_vocab * vocab) {
4376    return vocab->token_fim_pad();
4377}
4378
4379llama_token llama_vocab_fim_rep(const struct llama_vocab * vocab) {
4380    return vocab->token_fim_rep();
4381}
4382
4383llama_token llama_vocab_fim_sep(const struct llama_vocab * vocab) {
4384    return vocab->token_fim_sep();
4385}
4386
4387llama_token llama_vocab_mask(const struct llama_vocab* vocab) {
4388    return vocab->token_mask();
4389}
4390
4391// deprecated
4392const char * llama_token_get_text(const struct llama_vocab * vocab, llama_token token) {
4393    return llama_vocab_get_text(vocab, token);
4394}
4395
4396// deprecated
4397float llama_token_get_score(const struct llama_vocab * vocab, llama_token token) {
4398    return 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) {
4403    return llama_vocab_get_attr(vocab, token);
4404}
4405
4406// deprecated
4407bool llama_token_is_eog(const struct llama_vocab * vocab, llama_token token) {
4408    return llama_vocab_is_eog(vocab, token);
4409}
4410
4411// deprecated
4412bool llama_token_is_control(const struct llama_vocab * vocab, llama_token token) {
4413    return llama_vocab_is_control(vocab, token);
4414}
4415
4416// deprecated
4417llama_token llama_token_bos(const struct llama_vocab * vocab) {
4418    return llama_vocab_bos(vocab);
4419}
4420
4421// deprecated
4422llama_token llama_token_eos(const struct llama_vocab * vocab) {
4423    return llama_vocab_eos(vocab);
4424}
4425
4426// deprecated
4427llama_token llama_token_eot(const struct llama_vocab * vocab) {
4428    return llama_vocab_eot(vocab);
4429}
4430
4431// deprecated
4432llama_token llama_token_cls(const struct llama_vocab * vocab) {
4433    //return llama_vocab_cls(vocab);
4434    return llama_vocab_bos(vocab); // avoid deprecation warning
4435}
4436
4437// deprecated
4438llama_token llama_token_sep(const struct llama_vocab * vocab) {
4439    return llama_vocab_sep(vocab);
4440}
4441
4442// deprecated
4443llama_token llama_token_nl (const struct llama_vocab * vocab) {
4444    return llama_vocab_nl(vocab);
4445}
4446
4447// deprecated
4448llama_token llama_token_pad(const struct llama_vocab * vocab) {
4449    return llama_vocab_pad(vocab);
4450}
4451
4452// deprecated
4453bool llama_add_bos_token(const struct llama_vocab * vocab) {
4454    return llama_vocab_get_add_bos(vocab);
4455}
4456
4457// deprecated
4458bool llama_add_eos_token(const struct llama_vocab * vocab) {
4459    return llama_vocab_get_add_eos(vocab);
4460}
4461
4462// deprecated
4463llama_token llama_token_fim_pre(const struct llama_vocab * vocab) {
4464    return llama_vocab_fim_pre(vocab);
4465}
4466
4467// deprecated
4468llama_token llama_token_fim_suf(const struct llama_vocab * vocab) {
4469    return llama_vocab_fim_suf(vocab);
4470}
4471
4472// deprecated
4473llama_token llama_token_fim_mid(const struct llama_vocab * vocab) {
4474    return llama_vocab_fim_mid(vocab);
4475}
4476
4477// deprecated
4478llama_token llama_token_fim_pad(const struct llama_vocab * vocab) {
4479    return llama_vocab_fim_pad(vocab);
4480}
4481
4482// deprecated
4483llama_token llama_token_fim_rep(const struct llama_vocab * vocab) {
4484    return llama_vocab_fim_rep(vocab);
4485}
4486
4487// deprecated
4488llama_token llama_token_fim_sep(const struct llama_vocab * vocab) {
4489    return llama_vocab_fim_sep(vocab);
4490}
4491
4492//
4493// tokenization
4494//
4495
4496int32_t llama_tokenize(
4497    const struct llama_vocab * vocab,
4498                  const char * text,
4499                     int32_t   text_len,
4500                 llama_token * tokens,
4501                     int32_t   n_tokens_max,
4502                        bool   add_special,
4503                        bool   parse_special) {
4504    return vocab->tokenize(text, text_len, tokens, n_tokens_max, add_special, parse_special);
4505}
4506
4507int32_t llama_token_to_piece(
4508    const struct llama_vocab * vocab,
4509                 llama_token   token,
4510                        char * buf,
4511                     int32_t   length,
4512                     int32_t   lstrip,
4513                        bool   special) {
4514    return vocab->token_to_piece(token, buf, length, lstrip, special);
4515}
4516
4517int32_t llama_detokenize(
4518    const struct llama_vocab * vocab,
4519           const llama_token * tokens,
4520                     int32_t   n_tokens,
4521                        char * text,
4522                     int32_t   text_len_max,
4523                        bool   remove_special,
4524                        bool   unparse_special) {
4525    return vocab->detokenize(tokens, n_tokens, text, text_len_max, remove_special, unparse_special);
4526}