char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Charlotte Somsupport aliceai_t5_moe98a01afd9

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