Coverage Report

Created: 2026-06-13 06:23

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