Qvinfor commited on
Commit
c941ae3
·
verified ·
1 Parent(s): e0ceb5c

Upload 2 files

Browse files
Files changed (2) hide show
  1. engine/src/bindings.cpp +51 -0
  2. engine/src/tokenizer.cpp +1122 -0
engine/src/bindings.cpp ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <pybind11/pybind11.h>
2
+ #include <pybind11/stl.h>
3
+ #include <pybind11/stl_bind.h>
4
+ #include "tokenizer.hpp"
5
+
6
+ namespace py = pybind11;
7
+
8
+ PYBIND11_MODULE(_cpp_tokenizer, m) {
9
+ m.doc() = "Fast C++ BPE tokenizer for curriculum-trained vocabularies";
10
+
11
+ py::class_<curriculum::Tokenizer>(m, "Tokenizer")
12
+ .def(py::init<>())
13
+ .def("load", &curriculum::Tokenizer::load,
14
+ py::arg("vocab_path"), py::arg("merges_path"),
15
+ "Load tokenizer from vocab.json and merges.txt files")
16
+ .def("encode", &curriculum::Tokenizer::encode,
17
+ py::arg("text"),
18
+ py::call_guard<py::gil_scoped_release>(),
19
+ "Encode text to list of token IDs")
20
+ .def("decode", &curriculum::Tokenizer::decode,
21
+ py::arg("ids"),
22
+ py::call_guard<py::gil_scoped_release>(),
23
+ "Decode list of token IDs to text")
24
+ .def("encode_batch", &curriculum::Tokenizer::encode_batch,
25
+ py::arg("texts"), py::arg("num_threads") = 0,
26
+ py::call_guard<py::gil_scoped_release>(),
27
+ "Batch encode multiple texts")
28
+ .def("set_cache_capacity", &curriculum::Tokenizer::set_cache_capacity,
29
+ py::arg("capacity"), "Set the bounded piece-cache capacity; zero disables caching")
30
+ .def("clear_cache", &curriculum::Tokenizer::clear_cache,
31
+ "Clear cached pieces and cache counters")
32
+ .def("cache_info", &curriculum::Tokenizer::cache_info,
33
+ "Get cache capacity, entries, hits, misses, and payload bytes")
34
+ .def("vocab_size", &curriculum::Tokenizer::vocab_size,
35
+ "Get vocabulary size")
36
+ .def("id_to_token", &curriculum::Tokenizer::id_to_token,
37
+ py::arg("id"),
38
+ "Get token string for an ID")
39
+ .def("token_to_id", &curriculum::Tokenizer::token_to_id,
40
+ py::arg("token"),
41
+ "Get ID for a token string (-1 if not found)")
42
+ .def("set_special_tokens", &curriculum::Tokenizer::set_special_tokens,
43
+ py::arg("tokens"),
44
+ "Register existing vocabulary tokens as atomic controls")
45
+ .def("set_special_token_aliases", &curriculum::Tokenizer::set_special_token_aliases,
46
+ py::arg("aliases"),
47
+ "Register explicit legacy decode-only aliases without changing learned tokens")
48
+ .def("configure_special_tokens", &curriculum::Tokenizer::configure_special_tokens,
49
+ py::arg("token_ids"), py::arg("aliases"), py::arg("expected_vocab_size"),
50
+ "Validate configured controls and append only explicitly declared legacy tail IDs");
51
+ }
engine/src/tokenizer.cpp ADDED
@@ -0,0 +1,1122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "tokenizer.hpp"
2
+
3
+ #include <algorithm>
4
+ #include <atomic>
5
+ #include <cctype>
6
+ #include <cstdio>
7
+ #include <fstream>
8
+ #include <exception>
9
+ #include <iterator>
10
+ #include <iostream>
11
+ #include <limits>
12
+ #include <queue>
13
+ #include <sstream>
14
+ #include <stdexcept>
15
+ #include <thread>
16
+ #include <unordered_set>
17
+
18
+ namespace curriculum {
19
+ namespace {
20
+
21
+ bool is_hex(char c) {
22
+ return std::isxdigit(static_cast<unsigned char>(c)) != 0;
23
+ }
24
+
25
+ int hex_value(char c) {
26
+ if (c >= '0' && c <= '9') return c - '0';
27
+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;
28
+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;
29
+ return -1;
30
+ }
31
+
32
+ std::string vocab_string_to_bytes(const std::string& display) {
33
+ std::string result;
34
+ result.reserve(display.size());
35
+
36
+ size_t i = 0;
37
+ while (i < display.size()) {
38
+ if (i + 5 < display.size() &&
39
+ display[i] == '<' && display[i + 1] == '0' &&
40
+ display[i + 2] == 'x' && is_hex(display[i + 3]) &&
41
+ is_hex(display[i + 4]) && display[i + 5] == '>') {
42
+ const int value = hex_value(display[i + 3]) * 16 + hex_value(display[i + 4]);
43
+ result.push_back(static_cast<char>(value));
44
+ i += 6;
45
+ } else {
46
+ result.push_back(display[i]);
47
+ ++i;
48
+ }
49
+ }
50
+ return result;
51
+ }
52
+
53
+ std::string bytes_to_vocab_string(const std::string& bytes) {
54
+ std::string result;
55
+ result.reserve(bytes.size());
56
+ for (unsigned char c : bytes) {
57
+ if (c >= 0x20 && c <= 0x7E &&
58
+ c != static_cast<unsigned char>('<')) {
59
+ result.push_back(static_cast<char>(c));
60
+ } else {
61
+ char buffer[7];
62
+ std::snprintf(buffer, sizeof(buffer), "<0x%02X>", c);
63
+ result += buffer;
64
+ }
65
+ }
66
+ return result;
67
+ }
68
+
69
+ void append_utf8(std::string& out, uint32_t cp) {
70
+ if (cp <= 0x7F) {
71
+ out.push_back(static_cast<char>(cp));
72
+ } else if (cp <= 0x7FF) {
73
+ out.push_back(static_cast<char>(0xC0 | (cp >> 6)));
74
+ out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
75
+ } else if (cp <= 0xFFFF) {
76
+ out.push_back(static_cast<char>(0xE0 | (cp >> 12)));
77
+ out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
78
+ out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
79
+ } else {
80
+ out.push_back(static_cast<char>(0xF0 | (cp >> 18)));
81
+ out.push_back(static_cast<char>(0x80 | ((cp >> 12) & 0x3F)));
82
+ out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
83
+ out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
84
+ }
85
+ }
86
+
87
+ bool parse_hex4(const std::string& input, size_t pos, uint32_t& value) {
88
+ if (pos + 4 > input.size()) return false;
89
+ value = 0;
90
+ for (size_t j = 0; j < 4; ++j) {
91
+ const int h = hex_value(input[pos + j]);
92
+ if (h < 0) return false;
93
+ value = (value << 4) | static_cast<uint32_t>(h);
94
+ }
95
+ return true;
96
+ }
97
+
98
+ bool parse_json_string(
99
+ const std::string& content,
100
+ size_t& i,
101
+ std::string& output
102
+ ) {
103
+ if (i >= content.size() || content[i] != '"') return false;
104
+ ++i;
105
+ output.clear();
106
+
107
+ while (i < content.size()) {
108
+ const char c = content[i++];
109
+
110
+ if (c == '"') return true;
111
+
112
+ if (c != '\\') {
113
+ output.push_back(c);
114
+ continue;
115
+ }
116
+
117
+ if (i >= content.size()) return false;
118
+
119
+ const char esc = content[i++];
120
+
121
+ switch (esc) {
122
+ case '"':
123
+ output.push_back('"');
124
+ break;
125
+
126
+ case '\\':
127
+ output.push_back('\\');
128
+ break;
129
+
130
+ case '/':
131
+ output.push_back('/');
132
+ break;
133
+
134
+ case 'b':
135
+ output.push_back('\b');
136
+ break;
137
+
138
+ case 'f':
139
+ output.push_back('\f');
140
+ break;
141
+
142
+ case 'n':
143
+ output.push_back('\n');
144
+ break;
145
+
146
+ case 'r':
147
+ output.push_back('\r');
148
+ break;
149
+
150
+ case 't':
151
+ output.push_back('\t');
152
+ break;
153
+
154
+ case 'u': {
155
+ uint32_t cp = 0;
156
+
157
+ if (!parse_hex4(content, i, cp)) {
158
+ return false;
159
+ }
160
+
161
+ i += 4;
162
+
163
+ // Handle a UTF-16 surrogate pair when present.
164
+ if (cp >= 0xD800 && cp <= 0xDBFF &&
165
+ i + 6 <= content.size() &&
166
+ content[i] == '\\' &&
167
+ content[i + 1] == 'u') {
168
+
169
+ uint32_t low = 0;
170
+
171
+ if (parse_hex4(content, i + 2, low) &&
172
+ low >= 0xDC00 &&
173
+ low <= 0xDFFF) {
174
+
175
+ cp = 0x10000 +
176
+ ((cp - 0xD800) << 10) +
177
+ (low - 0xDC00);
178
+
179
+ i += 6;
180
+ }
181
+ }
182
+
183
+ append_utf8(output, cp);
184
+ break;
185
+ }
186
+
187
+ default:
188
+ return false;
189
+ }
190
+ }
191
+
192
+ return false;
193
+ }
194
+
195
+ void skip_json_space(const std::string& content, size_t& i) {
196
+ while (i < content.size() &&
197
+ (content[i] == ' ' ||
198
+ content[i] == '\n' ||
199
+ content[i] == '\r' ||
200
+ content[i] == '\t')) {
201
+ ++i;
202
+ }
203
+ }
204
+
205
+ bool parse_vocab_json(
206
+ const std::string& content,
207
+ std::unordered_map<std::string, int32_t>& output
208
+ ) {
209
+ size_t i = 0;
210
+
211
+ skip_json_space(content, i);
212
+
213
+ if (i >= content.size() || content[i++] != '{') {
214
+ return false;
215
+ }
216
+
217
+ while (true) {
218
+ skip_json_space(content, i);
219
+
220
+ if (i < content.size() && content[i] == '}') {
221
+ return true;
222
+ }
223
+
224
+ std::string key;
225
+
226
+ if (!parse_json_string(content, i, key)) {
227
+ return false;
228
+ }
229
+
230
+ skip_json_space(content, i);
231
+
232
+ if (i >= content.size() || content[i++] != ':') {
233
+ return false;
234
+ }
235
+
236
+ skip_json_space(content, i);
237
+
238
+ if (i >= content.size() ||
239
+ !std::isdigit(static_cast<unsigned char>(content[i]))) {
240
+ return false;
241
+ }
242
+
243
+ int64_t value = 0;
244
+
245
+ while (i < content.size() &&
246
+ std::isdigit(static_cast<unsigned char>(content[i]))) {
247
+
248
+ value = value * 10 + (content[i++] - '0');
249
+
250
+ if (value > std::numeric_limits<int32_t>::max()) {
251
+ return false;
252
+ }
253
+ }
254
+
255
+ output.emplace(
256
+ std::move(key),
257
+ static_cast<int32_t>(value)
258
+ );
259
+
260
+ skip_json_space(content, i);
261
+
262
+ if (i < content.size() && content[i] == ',') {
263
+ ++i;
264
+ continue;
265
+ }
266
+
267
+ if (i < content.size() && content[i] == '}') {
268
+ return true;
269
+ }
270
+
271
+ return false;
272
+ }
273
+ }
274
+
275
+ struct CodePoint {
276
+ uint32_t value;
277
+ size_t length;
278
+ };
279
+
280
+ CodePoint decode_utf8(std::string_view text, size_t i) {
281
+ const auto first =
282
+ static_cast<unsigned char>(text[i]);
283
+
284
+ if (first < 0x80) {
285
+ return {first, 1};
286
+ }
287
+
288
+ auto continuation = [&](size_t offset) {
289
+ return i + offset < text.size() &&
290
+ (static_cast<unsigned char>(text[i + offset]) & 0xC0) == 0x80;
291
+ };
292
+
293
+ if ((first & 0xE0) == 0xC0 &&
294
+ continuation(1)) {
295
+
296
+ return {
297
+ static_cast<uint32_t>((first & 0x1F) << 6) |
298
+ (static_cast<unsigned char>(text[i + 1]) & 0x3F),
299
+ 2
300
+ };
301
+ }
302
+
303
+ if ((first & 0xF0) == 0xE0 &&
304
+ continuation(1) &&
305
+ continuation(2)) {
306
+
307
+ return {
308
+ static_cast<uint32_t>((first & 0x0F) << 12) |
309
+ static_cast<uint32_t>(
310
+ (static_cast<unsigned char>(text[i + 1]) & 0x3F) << 6
311
+ ) |
312
+ (static_cast<unsigned char>(text[i + 2]) & 0x3F),
313
+ 3
314
+ };
315
+ }
316
+
317
+ if ((first & 0xF8) == 0xF0 &&
318
+ continuation(1) &&
319
+ continuation(2) &&
320
+ continuation(3)) {
321
+
322
+ return {
323
+ static_cast<uint32_t>((first & 0x07) << 18) |
324
+ static_cast<uint32_t>(
325
+ (static_cast<unsigned char>(text[i + 1]) & 0x3F) << 12
326
+ ) |
327
+ static_cast<uint32_t>(
328
+ (static_cast<unsigned char>(text[i + 2]) & 0x3F) << 6
329
+ ) |
330
+ (static_cast<unsigned char>(text[i + 3]) & 0x3F),
331
+ 4
332
+ };
333
+ }
334
+
335
+ // Invalid UTF-8: preserve the byte as its own token.
336
+ return {first, 1};
337
+ }
338
+
339
+ bool is_shared_whitespace(uint32_t cp) {
340
+ return (cp >= 0x0009 && cp <= 0x000D) ||
341
+ cp == 0x0020 ||
342
+ cp == 0x0085 ||
343
+ cp == 0x00A0 ||
344
+ cp == 0x1680 ||
345
+ (cp >= 0x2000 && cp <= 0x200A) ||
346
+ cp == 0x2028 ||
347
+ cp == 0x2029 ||
348
+ cp == 0x202F ||
349
+ cp == 0x205F ||
350
+ cp == 0x3000;
351
+ }
352
+
353
+ constexpr size_t kMaxNonWhitespaceBytes = 256;
354
+
355
+ uint64_t pair_key(int32_t left, int32_t right) {
356
+ return (
357
+ static_cast<uint64_t>(
358
+ static_cast<uint32_t>(left)
359
+ ) << 32
360
+ ) |
361
+ static_cast<uint32_t>(right);
362
+ }
363
+
364
+ constexpr uint32_t kNoNode =
365
+ std::numeric_limits<uint32_t>::max();
366
+
367
+ struct MergeHeapEntry {
368
+ size_t rank;
369
+ uint32_t left_node;
370
+ uint64_t generation;
371
+ };
372
+
373
+ struct MergeHeapEntryGreater {
374
+ bool operator()(
375
+ const MergeHeapEntry& a,
376
+ const MergeHeapEntry& b
377
+ ) const {
378
+ if (a.rank != b.rank) {
379
+ return a.rank > b.rank;
380
+ }
381
+
382
+ return a.left_node > b.left_node;
383
+ }
384
+ };
385
+
386
+ } // namespace
387
+
388
+ struct Tokenizer::EncodingScratch {
389
+ std::vector<int32_t> tokens, encoded, legacy_next;
390
+ std::vector<uint32_t> previous, next;
391
+ std::vector<uint64_t> generation;
392
+ std::vector<MergeHeapEntry> heap;
393
+ };
394
+
395
+ bool Tokenizer::load(
396
+ const std::string& vocab_path,
397
+ const std::string& merges_path
398
+ ) {
399
+ std::unique_lock<std::shared_mutex> lock(model_mutex_);
400
+ invalidate_cache();
401
+ id_to_token_.clear();
402
+ token_to_id_.clear();
403
+ merges_.clear();
404
+ merge_lookup_.clear();
405
+ fast_merge_order_ = true;
406
+ special_tokens_.clear();
407
+ special_token_aliases_.clear();
408
+
409
+ if (!load_vocab(vocab_path)) {
410
+ std::cerr
411
+ << "Failed to load vocab from "
412
+ << vocab_path
413
+ << '\n';
414
+
415
+ return false;
416
+ }
417
+
418
+ if (!load_merges(merges_path)) {
419
+ std::cerr
420
+ << "Failed to load merges from "
421
+ << merges_path
422
+ << '\n';
423
+
424
+ return false;
425
+ }
426
+
427
+ return true;
428
+ }
429
+
430
+ bool Tokenizer::load_vocab(const std::string& path) {
431
+ std::ifstream file(path, std::ios::binary);
432
+
433
+ if (!file) {
434
+ return false;
435
+ }
436
+
437
+ const std::string content(
438
+ (std::istreambuf_iterator<char>(file)),
439
+ std::istreambuf_iterator<char>()
440
+ );
441
+
442
+ std::unordered_map<std::string, int32_t> raw_vocab;
443
+
444
+ if (!parse_vocab_json(content, raw_vocab) ||
445
+ raw_vocab.empty()) {
446
+ return false;
447
+ }
448
+
449
+ int32_t max_id = -1;
450
+
451
+ for (const auto& entry : raw_vocab) {
452
+ max_id = std::max(
453
+ max_id,
454
+ entry.second
455
+ );
456
+ }
457
+
458
+ id_to_token_.assign(
459
+ static_cast<size_t>(max_id) + 1,
460
+ std::string{}
461
+ );
462
+
463
+ std::vector<bool> seen_ids(
464
+ id_to_token_.size(),
465
+ false
466
+ );
467
+
468
+ for (const auto& [display, id] : raw_vocab) {
469
+ if (id < 0 ||
470
+ static_cast<size_t>(id) >= id_to_token_.size()) {
471
+ return false;
472
+ }
473
+
474
+ const std::string bytes =
475
+ vocab_string_to_bytes(display);
476
+
477
+ if (bytes.empty()) {
478
+ std::cerr
479
+ << "Empty token in vocabulary at ID "
480
+ << id
481
+ << '\n';
482
+
483
+ return false;
484
+ }
485
+
486
+ if (seen_ids[static_cast<size_t>(id)]) {
487
+ std::cerr
488
+ << "Duplicate vocabulary ID "
489
+ << id
490
+ << '\n';
491
+
492
+ return false;
493
+ }
494
+
495
+ if (token_to_id_.find(bytes) !=
496
+ token_to_id_.end()) {
497
+
498
+ std::cerr
499
+ << "Duplicate vocabulary token bytes at ID "
500
+ << id
501
+ << '\n';
502
+
503
+ return false;
504
+ }
505
+
506
+ seen_ids[static_cast<size_t>(id)] = true;
507
+
508
+ id_to_token_[id] = bytes;
509
+ token_to_id_[bytes] = id;
510
+ }
511
+
512
+ for (size_t id = 0; id < seen_ids.size(); ++id) {
513
+ if (!seen_ids[id]) {
514
+ std::cerr
515
+ << "Missing vocabulary ID "
516
+ << id
517
+ << '\n';
518
+
519
+ return false;
520
+ }
521
+ }
522
+
523
+ for (int32_t id = 0; id < 256; ++id) {
524
+ if (static_cast<size_t>(id) >=
525
+ id_to_token_.size()) {
526
+ return false;
527
+ }
528
+
529
+ const std::string expected(
530
+ 1,
531
+ static_cast<char>(id)
532
+ );
533
+
534
+ if (id_to_token_[id] != expected) {
535
+ std::cerr
536
+ << "Invalid base-byte token at ID "
537
+ << id
538
+ << '\n';
539
+
540
+ return false;
541
+ }
542
+ }
543
+
544
+ return true;
545
+ }
546
+
547
+ bool Tokenizer::load_merges(
548
+ const std::string& path
549
+ ) {
550
+ std::ifstream file(path);
551
+
552
+ if (!file) {
553
+ return false;
554
+ }
555
+
556
+ merge_lookup_.clear();
557
+ fast_merge_order_ = true;
558
+
559
+ int32_t previous_result = 255;
560
+
561
+ std::string line;
562
+ size_t line_number = 0;
563
+
564
+ while (std::getline(file, line)) {
565
+ ++line_number;
566
+
567
+ if (line.empty() ||
568
+ line[0] == '#') {
569
+ continue;
570
+ }
571
+
572
+ int64_t left = -1;
573
+ int64_t right = -1;
574
+ int64_t result = -1;
575
+
576
+ std::istringstream stream(line);
577
+ std::string extra;
578
+
579
+ if (!(stream >> left >> right >> result) ||
580
+ (stream >> extra)) {
581
+
582
+ std::cerr
583
+ << "Invalid merge rule at line "
584
+ << line_number
585
+ << '\n';
586
+
587
+ return false;
588
+ }
589
+
590
+ const auto valid_id = [&](int64_t id) {
591
+ return id >= 0 &&
592
+ static_cast<size_t>(id) <
593
+ id_to_token_.size();
594
+ };
595
+
596
+ if (!valid_id(left) ||
597
+ !valid_id(right) ||
598
+ !valid_id(result)) {
599
+
600
+ std::cerr
601
+ << "Out-of-range merge ID at line "
602
+ << line_number
603
+ << '\n';
604
+
605
+ return false;
606
+ }
607
+
608
+ const std::string expected =
609
+ id_to_token_[left] +
610
+ id_to_token_[right];
611
+
612
+ if (id_to_token_[result] != expected) {
613
+ std::cerr
614
+ << "Merge result bytes do not match at line "
615
+ << line_number
616
+ << '\n';
617
+
618
+ return false;
619
+ }
620
+
621
+ const int32_t left_id =
622
+ static_cast<int32_t>(left);
623
+
624
+ const int32_t right_id =
625
+ static_cast<int32_t>(right);
626
+
627
+ const int32_t result_id =
628
+ static_cast<int32_t>(result);
629
+
630
+ const size_t rank =
631
+ merges_.size();
632
+
633
+ // A trained vocabulary assigns monotonically increasing IDs to merge
634
+ // results. That makes newly-created pairs strictly later rules, which
635
+ // is the condition needed by the indexed heap encoder below. Keep the
636
+ // legacy path for unusual hand-authored files.
637
+ if (result_id <= previous_result ||
638
+ result_id <= left_id ||
639
+ result_id <= right_id) {
640
+
641
+ fast_merge_order_ = false;
642
+ }
643
+
644
+ previous_result = result_id;
645
+
646
+ const auto [_, inserted] =
647
+ merge_lookup_.emplace(
648
+ pair_key(left_id, right_id),
649
+ MergeInfo{rank, result_id}
650
+ );
651
+
652
+ if (!inserted) {
653
+ fast_merge_order_ = false;
654
+ }
655
+
656
+ merges_.emplace_back(
657
+ left_id,
658
+ right_id,
659
+ result_id
660
+ );
661
+ }
662
+
663
+ return true;
664
+ }
665
+
666
+ void Tokenizer::encode_word_into(std::string_view bytes, EncodingScratch& scratch) const {
667
+ auto& tokens = scratch.tokens;
668
+ auto& encoded = scratch.encoded;
669
+ tokens.resize(bytes.size());
670
+ // char may be signed; byte IDs must remain in [0, 255].
671
+ for (size_t i = 0; i < bytes.size(); ++i) tokens[i] = static_cast<unsigned char>(bytes[i]);
672
+ encoded.clear();
673
+ if (tokens.size() < 2 || merges_.empty()) {
674
+ encoded.assign(tokens.begin(), tokens.end());
675
+ return;
676
+ }
677
+ if (!fast_merge_order_) {
678
+ auto& next = scratch.legacy_next;
679
+ for (const auto& [left, right, result] : merges_) {
680
+ next.clear();
681
+ for (size_t i = 0; i < tokens.size();) {
682
+ if (i + 1 < tokens.size() && tokens[i] == left && tokens[i + 1] == right) {
683
+ next.push_back(result);
684
+ i += 2;
685
+ } else next.push_back(tokens[i++]);
686
+ }
687
+ tokens.swap(next);
688
+ }
689
+ encoded.assign(tokens.begin(), tokens.end());
690
+ return;
691
+ }
692
+ if (tokens.size() == 2) {
693
+ const auto found = merge_lookup_.find(pair_key(tokens[0], tokens[1]));
694
+ if (found != merge_lookup_.end()) encoded.push_back(found->second.result);
695
+ else encoded.assign(tokens.begin(), tokens.end());
696
+ return;
697
+ }
698
+ if (tokens.size() >= kNoNode) throw std::length_error("pretoken piece exceeds node index range");
699
+ const size_t count = tokens.size();
700
+ auto& previous = scratch.previous;
701
+ auto& next = scratch.next;
702
+ auto& generation = scratch.generation;
703
+ auto& heap = scratch.heap;
704
+ previous.assign(count, kNoNode);
705
+ next.assign(count, kNoNode);
706
+ generation.assign(count, 0);
707
+ heap.clear();
708
+ for (uint32_t i = 0; i + 1 < count; ++i) {
709
+ next[i] = i + 1;
710
+ previous[i + 1] = i;
711
+ }
712
+ const size_t no_rank = std::numeric_limits<size_t>::max();
713
+ bool heap_ready = false;
714
+ auto enqueue = [&](uint32_t left, size_t completed_rank) {
715
+ if (left == kNoNode || next[left] == kNoNode) return;
716
+ const auto found = merge_lookup_.find(pair_key(tokens[left], tokens[next[left]]));
717
+ if (found == merge_lookup_.end() ||
718
+ (completed_rank != no_rank && found->second.rank <= completed_rank)) return;
719
+ heap.push_back({found->second.rank, left, generation[left]});
720
+ if (heap_ready) std::push_heap(heap.begin(), heap.end(), MergeHeapEntryGreater{});
721
+ };
722
+ for (uint32_t i = 0; i + 1 < count; ++i) enqueue(i, no_rank);
723
+ std::make_heap(heap.begin(), heap.end(), MergeHeapEntryGreater{});
724
+ heap_ready = true;
725
+ auto pop = [&]() {
726
+ std::pop_heap(heap.begin(), heap.end(), MergeHeapEntryGreater{});
727
+ const auto entry = heap.back();
728
+ heap.pop_back();
729
+ return entry;
730
+ };
731
+ size_t completed_rank = no_rank;
732
+ while (!heap.empty()) {
733
+ const auto first = pop();
734
+ if (completed_rank != no_rank && first.rank <= completed_rank) continue;
735
+ const size_t rank = first.rank;
736
+ completed_rank = rank;
737
+ auto merge_if_current = [&](const MergeHeapEntry& entry) {
738
+ if (entry.left_node >= count || generation[entry.left_node] != entry.generation) return;
739
+ const uint32_t left = entry.left_node;
740
+ const uint32_t right = next[left];
741
+ if (right == kNoNode) return;
742
+ const auto found = merge_lookup_.find(pair_key(tokens[left], tokens[right]));
743
+ if (found == merge_lookup_.end() || found->second.rank != rank) return;
744
+ const uint32_t before = previous[left];
745
+ const uint32_t after = next[right];
746
+ tokens[left] = found->second.result;
747
+ next[left] = after;
748
+ if (after != kNoNode) previous[after] = left;
749
+ next[right] = previous[right] = kNoNode;
750
+ ++generation[left];
751
+ ++generation[right];
752
+ if (before != kNoNode) ++generation[before];
753
+ enqueue(before, rank);
754
+ enqueue(left, rank);
755
+ };
756
+ merge_if_current(first);
757
+ while (!heap.empty() && heap.front().rank == rank) merge_if_current(pop());
758
+ }
759
+ for (uint32_t node = 0; node != kNoNode; node = next[node]) encoded.push_back(tokens[node]);
760
+ }
761
+
762
+ void Tokenizer::append_word(std::string_view bytes, std::vector<int32_t>& output,
763
+ EncodingScratch& scratch) const {
764
+ if (bytes.size() == 1) {
765
+ output.push_back(static_cast<unsigned char>(bytes[0]));
766
+ return;
767
+ }
768
+ if (cache_capacity_ == 0 || bytes.size() > kMaxCachedPieceBytes) {
769
+ encode_word_into(bytes, scratch);
770
+ output.insert(output.end(), scratch.encoded.begin(), scratch.encoded.end());
771
+ return;
772
+ }
773
+ const size_t shard_id = std::hash<std::string_view>{}(bytes) % kCacheShards;
774
+ const size_t capacity = cache_capacity_ / kCacheShards + (shard_id < cache_capacity_ % kCacheShards);
775
+ const bool cacheable = capacity != 0;
776
+ auto& shard = piece_cache_[shard_id];
777
+ if (cacheable) {
778
+ std::lock_guard<std::mutex> lock(shard.mutex);
779
+ const auto found = shard.index.find(bytes);
780
+ if (found != shard.index.end()) {
781
+ ++shard.hits;
782
+ shard.lru.splice(shard.lru.begin(), shard.lru, found->second);
783
+ const auto& ids = found->second->ids;
784
+ output.insert(output.end(), ids.begin(), ids.end());
785
+ return;
786
+ }
787
+ ++shard.misses;
788
+ }
789
+ encode_word_into(bytes, scratch);
790
+ const auto& ids = scratch.encoded;
791
+ if (cacheable) {
792
+ std::lock_guard<std::mutex> lock(shard.mutex);
793
+ // Another encoding thread can have filled this exact piece meanwhile.
794
+ if (shard.index.find(bytes) == shard.index.end()) {
795
+ shard.lru.push_front({std::string(bytes), ids});
796
+ try {
797
+ shard.index.emplace(std::string_view(shard.lru.front().bytes), shard.lru.begin());
798
+ } catch (...) {
799
+ shard.lru.pop_front();
800
+ throw;
801
+ }
802
+ shard.payload_bytes += bytes.size() + ids.size() * sizeof(int32_t);
803
+ while (shard.lru.size() > capacity || shard.payload_bytes > kCachePayloadBytes / kCacheShards) {
804
+ const auto last = std::prev(shard.lru.end());
805
+ shard.payload_bytes -= last->bytes.size() + last->ids.size() * sizeof(int32_t);
806
+ shard.index.erase(std::string_view(last->bytes));
807
+ shard.lru.erase(last);
808
+ }
809
+ }
810
+ }
811
+ output.insert(output.end(), ids.begin(), ids.end());
812
+ }
813
+
814
+ void Tokenizer::append_regular(std::string_view text, std::vector<int32_t>& output,
815
+ EncodingScratch& scratch) const {
816
+ size_t i = 0;
817
+ while (i < text.size()) {
818
+ const size_t start = i;
819
+ while (i < text.size()) {
820
+ const auto cp = decode_utf8(text, i);
821
+ if (!is_shared_whitespace(cp.value)) break;
822
+ i += cp.length;
823
+ }
824
+ const size_t field_start = i;
825
+ while (i < text.size()) {
826
+ const auto cp = decode_utf8(text, i);
827
+ if (is_shared_whitespace(cp.value) ||
828
+ (i > field_start && i + cp.length - field_start > kMaxNonWhitespaceBytes)) break;
829
+ i += cp.length;
830
+ }
831
+ append_word(text.substr(start, i - start), output, scratch);
832
+ }
833
+ }
834
+
835
+ std::vector<int32_t> Tokenizer::encode_impl(const std::string& text) const {
836
+ // Scratch holds only temporary arrays; cached results belong to the model.
837
+ thread_local EncodingScratch scratch;
838
+ std::vector<int32_t> output;
839
+ output.reserve(text.size() / 3 + 8);
840
+ const std::string_view view(text);
841
+ if (special_tokens_.empty()) append_regular(view, output, scratch);
842
+ else {
843
+ size_t cursor = 0;
844
+ while (cursor < text.size()) {
845
+ size_t position = std::string::npos, length = 0;
846
+ int32_t id = -1;
847
+ for (const auto& special : special_tokens_) {
848
+ const size_t found = text.find(special.first, cursor);
849
+ if (found < position || (found != std::string::npos && found == position && special.first.size() > length)) {
850
+ position = found;
851
+ length = special.first.size();
852
+ id = special.second;
853
+ }
854
+ }
855
+ if (position == std::string::npos) {
856
+ append_regular(view.substr(cursor), output, scratch);
857
+ break;
858
+ }
859
+ append_regular(view.substr(cursor, position - cursor), output, scratch);
860
+ output.push_back(id);
861
+ cursor = position + length;
862
+ }
863
+ }
864
+ // A giant whitespace run must not permanently pin a giant per-thread arena.
865
+ if (scratch.tokens.capacity() > 4096 || scratch.encoded.capacity() > 4096 ||
866
+ scratch.legacy_next.capacity() > 4096 || scratch.heap.capacity() > 16384) scratch = EncodingScratch{};
867
+ return output;
868
+ }
869
+
870
+ std::vector<int32_t> Tokenizer::encode(const std::string& text) const {
871
+ std::shared_lock<std::shared_mutex> lock(model_mutex_);
872
+ return encode_impl(text);
873
+ }
874
+
875
+ void Tokenizer::invalidate_cache() {
876
+ for (auto& shard : piece_cache_) {
877
+ std::lock_guard<std::mutex> lock(shard.mutex);
878
+ shard.index.clear();
879
+ shard.lru.clear();
880
+ shard.payload_bytes = shard.hits = shard.misses = 0;
881
+ }
882
+ }
883
+
884
+ void Tokenizer::set_cache_capacity(size_t capacity) {
885
+ if (capacity > 1048576) throw std::invalid_argument("cache capacity exceeds 1048576 pieces");
886
+ std::unique_lock<std::shared_mutex> lock(model_mutex_);
887
+ invalidate_cache();
888
+ cache_capacity_ = capacity;
889
+ }
890
+
891
+ void Tokenizer::clear_cache() {
892
+ std::unique_lock<std::shared_mutex> lock(model_mutex_);
893
+ invalidate_cache();
894
+ }
895
+
896
+ std::unordered_map<std::string, size_t> Tokenizer::cache_info() const {
897
+ std::shared_lock<std::shared_mutex> model_lock(model_mutex_);
898
+ std::unordered_map<std::string, size_t> result{
899
+ {"capacity", cache_capacity_}, {"entries", 0}, {"hits", 0}, {"misses", 0},
900
+ {"payload_bytes", 0}, {"max_payload_bytes", kCachePayloadBytes}};
901
+ for (auto& shard : piece_cache_) {
902
+ std::lock_guard<std::mutex> lock(shard.mutex);
903
+ result["entries"] += shard.index.size();
904
+ result["hits"] += shard.hits;
905
+ result["misses"] += shard.misses;
906
+ result["payload_bytes"] += shard.payload_bytes;
907
+ }
908
+ return result;
909
+ }
910
+
911
+ size_t Tokenizer::vocab_size() const {
912
+ std::shared_lock<std::shared_mutex> lock(model_mutex_);
913
+ return id_to_token_.size();
914
+ }
915
+
916
+ std::string Tokenizer::decode(
917
+ const std::vector<int32_t>& ids
918
+ ) const {
919
+ std::shared_lock<std::shared_mutex> lock(model_mutex_);
920
+ std::string result;
921
+
922
+ for (int32_t id : ids) {
923
+ if (id < 0 ||
924
+ static_cast<size_t>(id) >=
925
+ id_to_token_.size()) {
926
+
927
+ throw std::out_of_range(
928
+ "token ID out of vocabulary range"
929
+ );
930
+ }
931
+
932
+ const auto alias = special_token_aliases_.find(id);
933
+ result += alias == special_token_aliases_.end() ? id_to_token_[id] : alias->second;
934
+ }
935
+
936
+ return result;
937
+ }
938
+
939
+ std::vector<std::vector<int32_t>>
940
+ Tokenizer::encode_batch(
941
+ const std::vector<std::string>& texts, size_t num_threads
942
+ ) const {
943
+ if (num_threads > 64) throw std::invalid_argument("num_threads must be between 0 and 64");
944
+ std::shared_lock<std::shared_mutex> lock(model_mutex_);
945
+ std::vector<std::vector<int32_t>> result(texts.size());
946
+ size_t workers = num_threads;
947
+ if (workers == 0) {
948
+ size_t bytes = 0;
949
+ for (const auto& text : texts) bytes += text.size();
950
+ workers = bytes >= 256 * 1024 ? std::min<size_t>(4, std::max(1u, std::thread::hardware_concurrency())) : 1;
951
+ }
952
+ workers = std::min(workers, texts.size());
953
+ if (workers <= 1) {
954
+ for (size_t i = 0; i < texts.size(); ++i) result[i] = encode_impl(texts[i]);
955
+ return result;
956
+ }
957
+ std::atomic<size_t> cursor{0};
958
+ std::atomic<bool> failed{false};
959
+ std::exception_ptr error;
960
+ std::mutex error_mutex;
961
+ auto work = [&]() {
962
+ try {
963
+ while (!failed.load(std::memory_order_relaxed)) {
964
+ const size_t i = cursor.fetch_add(1, std::memory_order_relaxed);
965
+ if (i >= texts.size()) break;
966
+ result[i] = encode_impl(texts[i]);
967
+ }
968
+ } catch (...) {
969
+ std::lock_guard<std::mutex> error_lock(error_mutex);
970
+ if (!error) error = std::current_exception();
971
+ failed.store(true, std::memory_order_relaxed);
972
+ }
973
+ };
974
+ std::vector<std::thread> threads;
975
+ try {
976
+ for (size_t i = 1; i < workers; ++i) threads.emplace_back(work);
977
+ } catch (...) {
978
+ failed.store(true, std::memory_order_relaxed);
979
+ for (auto& thread : threads) thread.join();
980
+ throw;
981
+ }
982
+ work();
983
+ for (auto& thread : threads) thread.join();
984
+ if (error) std::rethrow_exception(error);
985
+ return result;
986
+ }
987
+
988
+ std::string Tokenizer::id_to_token(
989
+ int32_t id
990
+ ) const {
991
+ std::shared_lock<std::shared_mutex> lock(model_mutex_);
992
+ if (id < 0 ||
993
+ static_cast<size_t>(id) >=
994
+ id_to_token_.size()) {
995
+ return {};
996
+ }
997
+
998
+ const auto alias = special_token_aliases_.find(id);
999
+ return bytes_to_vocab_string(alias == special_token_aliases_.end() ? id_to_token_[id] : alias->second);
1000
+ }
1001
+
1002
+ int32_t Tokenizer::token_to_id(
1003
+ const std::string& token
1004
+ ) const {
1005
+ std::shared_lock<std::shared_mutex> lock(model_mutex_);
1006
+ const auto it =
1007
+ token_to_id_.find(token);
1008
+
1009
+ return it == token_to_id_.end()
1010
+ ? -1
1011
+ : it->second;
1012
+ }
1013
+
1014
+ void Tokenizer::set_special_tokens(
1015
+ const std::vector<std::string>& tokens
1016
+ ) {
1017
+ std::unique_lock<std::shared_mutex> lock(model_mutex_);
1018
+ std::unordered_map<std::string, int32_t> configured;
1019
+ for (const auto& token : tokens) {
1020
+ const auto found = token_to_id_.find(token);
1021
+ if (token.empty() || found == token_to_id_.end() || found->second < 256) {
1022
+ throw std::invalid_argument("special token is missing from the loaded vocabulary: " + token);
1023
+ }
1024
+ if (!configured.emplace(token, found->second).second) {
1025
+ throw std::invalid_argument("duplicate special token: " + token);
1026
+ }
1027
+ for (const auto& [left, right, result] : merges_) {
1028
+ if (left == found->second || right == found->second || result == found->second) {
1029
+ throw std::invalid_argument("special token ID participates in an ordinary merge: " + token);
1030
+ }
1031
+ }
1032
+ }
1033
+ invalidate_cache();
1034
+ special_tokens_ = std::move(configured);
1035
+ special_token_aliases_.clear();
1036
+ }
1037
+
1038
+ void Tokenizer::configure_special_tokens(
1039
+ const std::unordered_map<std::string, int32_t>& token_ids,
1040
+ const std::unordered_map<int32_t, std::string>& aliases,
1041
+ size_t expected_vocab_size
1042
+ ) {
1043
+ std::unique_lock<std::shared_mutex> lock(model_mutex_);
1044
+ // Legacy artifacts may keep tail controls in metadata rather than vocab.json.
1045
+ // Validate every addition before committing; existing ordinary IDs are immutable.
1046
+ std::unordered_map<int32_t, std::string> additions;
1047
+ std::unordered_set<int32_t> protected_ids;
1048
+ size_t final_size = id_to_token_.size();
1049
+ for (const auto& [token, id] : token_ids) {
1050
+ if (token.empty() || id < 256 || !protected_ids.insert(id).second) {
1051
+ throw std::invalid_argument("invalid or duplicate canonical special-token ID");
1052
+ }
1053
+ const auto existing = token_to_id_.find(token);
1054
+ if (existing != token_to_id_.end() && existing->second != id) {
1055
+ throw std::invalid_argument("configured special-token ID disagrees with vocabulary");
1056
+ }
1057
+ if (static_cast<size_t>(id) < id_to_token_.size()) {
1058
+ if (id_to_token_[id] != token) {
1059
+ throw std::invalid_argument("special token would overwrite an existing vocabulary ID");
1060
+ }
1061
+ } else {
1062
+ additions.emplace(id, token);
1063
+ }
1064
+ final_size = std::max(final_size, static_cast<size_t>(id) + 1);
1065
+ }
1066
+ for (const auto& [id, token] : aliases) {
1067
+ if (id < 256 || token_ids.find(token) == token_ids.end() ||
1068
+ !protected_ids.insert(id).second) {
1069
+ throw std::invalid_argument("invalid or conflicting decode-only alias");
1070
+ }
1071
+ if (static_cast<size_t>(id) >= id_to_token_.size()) {
1072
+ additions.emplace(id, token);
1073
+ }
1074
+ final_size = std::max(final_size, static_cast<size_t>(id) + 1);
1075
+ }
1076
+ if (final_size != expected_vocab_size ||
1077
+ final_size - id_to_token_.size() != additions.size()) {
1078
+ throw std::invalid_argument("configured vocabulary size disagrees with vocabulary and explicit controls");
1079
+ }
1080
+ for (const auto& [left, right, result] : merges_) {
1081
+ if (protected_ids.count(left) || protected_ids.count(right) || protected_ids.count(result)) {
1082
+ throw std::invalid_argument("configured control or alias ID participates in an ordinary merge");
1083
+ }
1084
+ }
1085
+ // Unique additions with the correct span count are necessarily contiguous.
1086
+ id_to_token_.reserve(final_size);
1087
+ for (size_t id = id_to_token_.size(); id < final_size; ++id) {
1088
+ id_to_token_.push_back(additions.at(static_cast<int32_t>(id)));
1089
+ }
1090
+ for (const auto& [token, id] : token_ids) {
1091
+ token_to_id_.emplace(token, id);
1092
+ }
1093
+ invalidate_cache();
1094
+ special_tokens_ = token_ids;
1095
+ special_token_aliases_ = aliases;
1096
+ }
1097
+
1098
+ void Tokenizer::set_special_token_aliases(
1099
+ const std::unordered_map<int32_t, std::string>& aliases
1100
+ ) {
1101
+ std::unique_lock<std::shared_mutex> lock(model_mutex_);
1102
+ for (const auto& [id, token] : aliases) {
1103
+ if (id < 256 || static_cast<size_t>(id) >= id_to_token_.size() ||
1104
+ special_tokens_.find(token) == special_tokens_.end()) {
1105
+ throw std::invalid_argument("invalid decode-only special-token alias");
1106
+ }
1107
+ for (const auto& special : special_tokens_) {
1108
+ if (special.second == id) {
1109
+ throw std::invalid_argument("decode-only alias conflicts with a canonical special ID");
1110
+ }
1111
+ }
1112
+ for (const auto& [left, right, result] : merges_) {
1113
+ if (left == id || right == id || result == id) {
1114
+ throw std::invalid_argument("decode-only alias would replace a learned token ID");
1115
+ }
1116
+ }
1117
+ }
1118
+ invalidate_cache();
1119
+ special_token_aliases_ = aliases;
1120
+ }
1121
+
1122
+ } // namespace curriculum