Coverage Report

Created: 2026-03-21 06:50

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