Coverage Report

Created: 2026-01-17 06:04

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