Coverage Report

Created: 2026-01-10 06:25

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