-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtokenizer.cpp
More file actions
2436 lines (2117 loc) · 114 KB
/
Copy pathtokenizer.cpp
File metadata and controls
2436 lines (2117 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "tokenizer.h"
#include <algorithm>
#include <cctype>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <nlohmann/json.hpp>
#include <queue>
#include <boost/regex.hpp>
#include <boost/xpressive/xpressive.hpp>
#include <sstream>
#include <stdexcept>
#include <unordered_set>
#include <vector>
#include <string>
#include <limits>
#include <utility> // For std::pair
#include <functional> // For std::less
#include <filesystem>
#include "logger.h"
// Define BPE_SPACE_CHAR at file scope for broader accessibility
const std::string BPE_SPACE_CHAR = "\xC4\xA0"; // GPT-2 BPE space character (Ġ)
using json = nlohmann::json;
// Forward declaration for helper function defined later in an anonymous namespace
namespace {
size_t unicode_char_len(char src);
} // end anonymous namespace
// Helper function to check if a string represents a number.
bool is_numeric(const std::string& s) {
if (s.empty()) {
return false; // An empty string is not considered numeric
}
for (char c : s) {
if (!std::isdigit(static_cast<unsigned char>(c))) {
return false; // Found a non-digit character
}
}
return true; // All characters are digits
}
// Finds the rank of a potential BPE merge.
// Returns the rank (lower is better) if the merge exists, otherwise -1.
int Tokenizer::find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
auto it = bpe_merges_.find(token_left + token_right); // Ensure this uses the correct combined form if prefixes are involved
if (it != bpe_merges_.end()) {
return it->second; // Return the rank
}
return -1; // Merge not found
}
std::vector<std::string> Tokenizer::bpe_tokenize_from_scores(
const std::string& text) const {
std::vector<std::string> all_tokens;
std::vector<std::string> initial_units; // Pre-tokenized parts (words, symbols, spaces)
// Llama-like regex for pre-tokenization
boost::regex llama_regex(
// This pattern is common for SentencePiece-like splitting by words, numbers, symbols, and whitespace.
R"([\r\n]+|[[:space:]]+|[^\r\n[:space:][:alnum:]]+|[[:alnum:]]+)");
boost::smatch match;
std::string text_to_search = text;
// Pre-tokenize the text using the regex
while (boost::regex_search(text_to_search, match, llama_regex)) {
if (!match.str(0).empty()) { // Ensure no empty strings are added
initial_units.push_back(match.str(0));
}
text_to_search = match.suffix().str();
}
if (!text_to_search.empty()) { // Add any trailing part not matched
initial_units.push_back(text_to_search);
}
Logger::debug("[BPE_SCORES] Regex pre-tokenization resulted in " + std::to_string(initial_units.size()) + " initial units.");
const std::string sp_space_prefix = "\xE2\x96\x81"; // SentencePiece space U+2581
bool next_word_needs_prefix = true;
for (const std::string& unit_raw : initial_units) {
if (unit_raw.empty()) continue;
// Check if the unit is purely whitespace
bool unit_is_whitespace = true;
for (char c : unit_raw) {
if (!std::isspace(static_cast<unsigned char>(c))) {
unit_is_whitespace = false;
break;
}
}
if (unit_is_whitespace) {
// Whitespace signals that the *next* non-whitespace unit needs the prefix.
next_word_needs_prefix = true;
Logger::debug("[BPE_SCORES] Unit '" + unit_raw + "' is whitespace. Setting prefix flag for next word.");
continue; // Skip to the next unit
}
std::string unit_to_bpe = unit_raw;
if (next_word_needs_prefix) {
unit_to_bpe = sp_space_prefix + unit_to_bpe;
Logger::debug("[BPE_SCORES] Prefixed unit: '" + unit_raw + "' -> '" + unit_to_bpe + "'");
next_word_needs_prefix = false; // Reset flag after applying prefix
} else {
Logger::debug("[BPE_SCORES] Processing unit without prefix: '" + unit_to_bpe + "'");
}
if (unit_raw == "\n") {
Logger::debug("[BPE_SCORES] Raw unit is newline. It will be split into chars. Current unit_to_bpe: '" + unit_to_bpe + "'");
// If a newline is a standalone token, it should be found. If it's part of merges, it will be handled.
}
std::vector<std::string> chars; // Characters/sub-units of the current unit_to_bpe
// Split unit_to_bpe into UTF-8 characters
for (size_t i = 0; i < unit_to_bpe.size();) {
int bytes = unicode_char_len(unit_to_bpe[i]);
if (i + bytes <= unit_to_bpe.size()) {
chars.push_back(unit_to_bpe.substr(i, bytes));
} else {
Logger::warning("[BPE_SCORES] Invalid UTF-8 sequence or length error for: '" + unit_to_bpe.substr(i) + "'");
chars.push_back(unit_to_bpe.substr(i));
break;
}
i += bytes;
}
if (chars.empty()) {
Logger::warning("[BPE_SCORES] Unit '" + unit_to_bpe + "' (original: '" + unit_raw + "') produced no chars for BPE.");
continue;
}
// Perform BPE merges based on scores (ranks in bpe_merges_)
bool changes = true;
while (changes && chars.size() > 1) {
changes = false;
int best_rank = std::numeric_limits<int>::max(); // For rank-based merges, lower is better
int best_i = -1;
for (size_t i = 0; i < chars.size() - 1; ++i) {
std::string pair = chars[i] + chars[i + 1];
auto it = bpe_merges_.find(pair);
if (it != bpe_merges_.end() && it->second < best_rank) { // Using rank from bpe_merges_
best_rank = it->second;
best_i = i;
}
}
if (best_i >= 0) { // If a merge was found
std::string merged = chars[best_i] + chars[best_i + 1];
chars[best_i] = merged;
chars.erase(chars.begin() + best_i + 1);
changes = true;
}
}
all_tokens.insert(all_tokens.end(), chars.begin(), chars.end());
}
Logger::debug("[BPE_SCORES] Final token count after BPE: " + std::to_string(all_tokens.size()));
return all_tokens;
}
std::vector<int> Tokenizer::tokens_to_ids(
const std::vector<std::string>& tokens) const {
std::vector<int> ids;
ids.reserve(tokens.size());
for (const auto& token : tokens) {
if (token == "\n") {
Logger::debug("[TOK_TO_ID_NL_DEBUG] Processing token: '\n' (actual newline char). Length: " + std::to_string(token.length()));
bool found_in_added = false;
for (const auto& pair : added_tokens_) {
if (pair.first == "\n") {
Logger::debug("[TOK_TO_ID_NL_DEBUG] Found '\n' key in added_tokens_ map. ID: " + std::to_string(pair.second));
found_in_added = true;
break;
}
}
if (!found_in_added) {
Logger::debug("[TOK_TO_ID_NL_DEBUG] '\n' key NOT found in added_tokens_ map by direct string compare.");
// Log all keys in added_tokens_ if newline is not found, to see what IS there
std::string keys_in_map = "Keys in added_tokens_: ";
for (const auto& pair : added_tokens_) {
std::string key_escaped;
for (char c_key : pair.first) {
if (c_key == '\n') key_escaped += "<NL>";
else if (c_key == '\r') key_escaped += "<CR>";
else if (c_key == '\t') key_escaped += "<TAB>";
else if (std::isprint(static_cast<unsigned char>(c_key))) key_escaped += c_key;
else { std::stringstream ss_hex; ss_hex << "<0x" << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(static_cast<unsigned char>(c_key)) << ">"; key_escaped += ss_hex.str(); }
}
keys_in_map += "['" + key_escaped + "' (len:" + std::to_string(pair.first.length()) + ")] ";
}
Logger::debug(keys_in_map);
}
}
auto added_it = added_tokens_.find(token);
if (added_it != added_tokens_.end()) { // Check added tokens first
ids.push_back(added_it->second);
Logger::debug("[TOK_TO_ID] Found added token: '" + token +
"' -> ID: " + std::to_string(added_it->second));
} else { // Not an added token, check base vocabulary
auto base_it = token_to_id_.find(token);
if (base_it != token_to_id_.end()) {
ids.push_back(base_it->second);
Logger::debug("[TOK_TO_ID] Found base token: '" + token +
"' -> ID: " + std::to_string(base_it->second));
} else { // Not in base vocab, try capitalized version
std::string capitalized_token = capitalize_first_letter(token);
if (capitalized_token != token) { // If capitalization changed something
auto capitalized_it = token_to_id_.find(capitalized_token);
if (capitalized_it != token_to_id_.end()) {
ids.push_back(capitalized_it->second);
Logger::debug(
"[TOK_TO_ID] FALLBACK: Found capitalized base token: '" +
token + "' -> '" + capitalized_token +
"' -> ID: " + std::to_string(capitalized_it->second));
continue; // Skip further fallbacks for this token
}
}
// Fallback for single-byte tokens if not found yet
if (token.length() == 1) {
char c = token[0];
auto byte_it = byte_char_to_id_.find(c);
if (byte_it != byte_char_to_id_.end()) {
ids.push_back(byte_it->second);
Logger::debug("[TOK_TO_ID] FALLBACK: Mapped single-byte token '" +
std::string(1, c) + "' to byte token ID " +
std::to_string(byte_it->second));
continue; // Skip further fallbacks
}
}
// If all fallbacks fail, use UNK token
Logger::debug("[TOK_TO_ID] UNKNOWN: Token '" + token +
"' not found in added, base, capitalized fallback, or "
"byte tokens. Using UNK ID: " +
std::to_string(unk_token_id_));
ids.push_back(unk_token_id_);
}
}
}
return ids;
}
std::vector<std::string> Tokenizer::ids_to_tokens(
const std::vector<int>& ids) const {
std::vector<std::string> tokens;
tokens.reserve(ids.size());
for (int id : ids) {
auto added_it = id_to_added_token_.find(id); // Check added tokens first
if (added_it != id_to_added_token_.end()) {
tokens.push_back(added_it->second);
} else if (id >= 0 && static_cast<size_t>(id) < id_to_token_.size()) { // Check base vocabulary
if (!id_to_token_[id].empty()) { // Ensure token string is not empty
tokens.push_back(id_to_token_[id]);
} else {
tokens.push_back(unk_token_); // Fallback to UNK string
Logger::warning(
"ID " + std::to_string(id) +
" found in base vocab range but has empty string. Using UNK token string: '" + unk_token_ + "'.");
}
} else { // ID is out of bounds or negative (and not an added token)
tokens.push_back(unk_token_); // Fallback to UNK string
}
}
return tokens;
}
Tokenizer::Tokenizer(const std::string& vocab_path,
const std::string& model_path,
const ModelConfig& config)
: tokenizer_family_(config.tokenizer_family),
unk_token_("<unk>"),
bos_token_("<s>"),
eos_token_("</s>"),
pad_token_("<pad>") {
Logger::info("[Tokenizer Constructor JSON] vocab_path: '" + vocab_path + "', model_path: '" + model_path + "'"); // Diagnostic log
try {
std::filesystem::path vocab_json_path_abs(vocab_path);
if (!std::filesystem::exists(vocab_json_path_abs)) {
throw std::runtime_error("Tokenizer vocab_path (tokenizer.json) does not exist: " + vocab_json_path_abs.string());
}
Logger::info(std::string("Loading tokenizer and vocab from: ") + vocab_json_path_abs.string());
std::string family_str = "UNKNOWN";
if (tokenizer_family_ == ModelConfig::TokenizerFamily::LLAMA_SENTENCEPIECE) family_str = "LLAMA_SENTENCEPIECE";
else if (tokenizer_family_ == ModelConfig::TokenizerFamily::LLAMA3_TIKTOKEN) family_str = "LLAMA3_TIKTOKEN";
Logger::info(std::string("Tokenizer family based on config: ") + family_str);
load_vocab_from_json(vocab_json_path_abs.string(), token_to_id_, id_to_token_);
if (tokenizer_family_ == ModelConfig::TokenizerFamily::LLAMA_SENTENCEPIECE) {
Logger::info("LLAMA_SENTENCEPIECE family detected for JSON constructor, attempting to load BPE merges from: " + vocab_json_path_abs.string());
load_bpe_merges_from_json(vocab_json_path_abs.string());
}
unk_token_id_ = (token_to_id_.count(unk_token_)) ? token_to_id_[unk_token_] : config.bos_token_id; // Fallback to BOS if UNK not in vocab
bos_token_id_ = (token_to_id_.count(bos_token_)) ? token_to_id_[bos_token_] : config.bos_token_id;
eos_token_id_ = (token_to_id_.count(eos_token_)) ? token_to_id_[eos_token_] : config.eos_token_id;
pad_token_id_ = (token_to_id_.count(pad_token_)) ? token_to_id_[pad_token_] : -1;
if (bos_token_id_ >= 0 && static_cast<size_t>(bos_token_id_) < id_to_token_.size() && !token_to_id_.count(bos_token_)) bos_token_ = id_to_token_[bos_token_id_];
if (eos_token_id_ >= 0 && static_cast<size_t>(eos_token_id_) < id_to_token_.size() && !token_to_id_.count(eos_token_)) eos_token_ = id_to_token_[eos_token_id_];
if (unk_token_id_ >= 0 && static_cast<size_t>(unk_token_id_) < id_to_token_.size() && !token_to_id_.count(unk_token_)) unk_token_ = id_to_token_[unk_token_id_];
if (pad_token_id_ >= 0 && static_cast<size_t>(pad_token_id_) < id_to_token_.size()) pad_token_ = id_to_token_[pad_token_id_];
Logger::info("Final Special Tokens (JSON constructor path): BOS=" + std::to_string(bos_token_id_) +
" ('" + bos_token_ + "'), EOS=" + std::to_string(eos_token_id_) + " ('" +
eos_token_ + "'), UNK=" + std::to_string(unk_token_id_) + " ('" +
unk_token_ + "'), PAD=" + std::to_string(pad_token_id_) + " ('" +
pad_token_ + "')"); // Removed extra backslashes from PAD log
std::string init_log_message = "Tokenizer successfully initialized from JSON/Config. Detected type based on config: ";
init_log_message += (tokenizer_family_ == ModelConfig::TokenizerFamily::LLAMA3_TIKTOKEN ? "LLAMA3_TIKTOKEN (assumed BPE)" :
(tokenizer_family_ == ModelConfig::TokenizerFamily::LLAMA_SENTENCEPIECE ? "LLAMA_SENTENCEPIECE (assumed BPE/SPM)" : "UNKNOWN"));
Logger::info(init_log_message);
if (model_path.size() > 0) {
if (model_path.size() > 6 &&
model_path.substr(model_path.size() - 6) == ".model") {
Logger::info("Loading SentencePiece model: " + model_path);
load_sentencepiece_model(model_path);
} else if (model_path.size() > 5 &&
model_path.substr(model_path.size() - 5) == ".json") {
Logger::info("Loading BPE merges from JSON: " + model_path);
load_bpe_merges_from_json(model_path);
} else {
Logger::info("Unsupported model format: " + model_path +
" - falling back to space tokenization");
}
} else {
Logger::info(
"No model path provided - falling back to space tokenization");
}
} catch (const std::exception& e) {
std::cerr << "Failed to load tokenizer or vocab from " << vocab_path << ": "
<< e.what() << std::endl;
Logger::error(std::string("Failed to load tokenizer or vocab from \"") +
vocab_path + "\": " + e.what());
throw;
}
if (id_to_token_.empty()) {
throw std::runtime_error(
"Failed to initialize tokenizer vocabulary from: " + vocab_path);
}
Logger::info("Loaded " + std::to_string(id_to_token_.size()) +
" tokens from vocabulary file: " + vocab_path);
if (id_to_token_.size() > 0) {
std::string first_few_tokens_log = "First few (up to 10 or vocab size) tokens from " + vocab_path + ": ";
for (size_t i = 0; i < std::min((size_t)10, id_to_token_.size()); ++i) {
first_few_tokens_log += "ID[" + std::to_string(i) + "]=";
std::string escaped_token;
for (char c_tok : id_to_token_[i]) {
if (c_tok == '\\') {
escaped_token += "\\\\";
} else if (c_tok == '\'') {
escaped_token += "\\'";
} else if (std::isprint(static_cast<unsigned char>(c_tok))) {
escaped_token += c_tok;
} else {
std::stringstream ss_hex;
ss_hex << "<0x" << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(static_cast<unsigned char>(c_tok)) << ">";
escaped_token += ss_hex.str();
}
}
first_few_tokens_log += "'" + escaped_token + "' "; // Enclose in single quotes
}
Logger::info(first_few_tokens_log);
}
const std::vector<std::pair<std::string, int>> known_chat_tokens = {
{"<|system|>", 32000}, {"<|user|>", 32001}, {"<|assistant|>", 32002}};
int manually_injected_count = 0;
size_t vocab_size = id_to_token_.size();
for (const auto& pair : known_chat_tokens) {
const std::string& tok = pair.first;
int id = pair.second;
if (added_tokens_.find(tok) == added_tokens_.end() &&
static_cast<size_t>(id) >= vocab_size) {
added_tokens_[tok] = id;
id_to_added_token_[id] = tok;
manually_injected_count++;
Logger::info("[MANUAL INJECT] Added missing chat token: '" + tok +
"' with assumed ID: " + std::to_string(id));
} else if (added_tokens_.find(tok) != added_tokens_.end()) {
Logger::debug("[MANUAL INJECT] Chat token '" + tok +
"' already loaded from JSON. Skipping injection.");
} else {
Logger::warning("[MANUAL INJECT] Cannot add chat token '" + tok +
"', assumed ID " + std::to_string(id) +
" clashes with loaded vocab size (" +
std::to_string(vocab_size) + ").");
}
}
if (manually_injected_count > 0) {
Logger::info("Manually injected " +
std::to_string(manually_injected_count) +
" missing chat tokens.");
}
}
static std::unordered_map<std::string, int> generate_bpe_merges_from_vocab_scores(
const std::vector<std::string>& id_to_token,
const std::vector<float>& token_scores) {
std::unordered_map<std::string, int> generated_merges;
if (token_scores.empty() || id_to_token.empty()) {
Logger::warning("Cannot generate BPE merges: empty scores or vocabulary");
return generated_merges;
}
Logger::info("Generating BPE merges from vocabulary and scores for older Llama models...");
// Create a list of tokens with their scores, sorted by score (higher score = higher priority)
std::vector<std::pair<float, std::string>> scored_tokens;
for (size_t id = 0; id < id_to_token.size(); ++id) {
if (id < token_scores.size()) {
const std::string& token = id_to_token[id];
// Skip special tokens and single characters
if (token.length() > 1 &&
token.find("<") == std::string::npos &&
token.find(">") == std::string::npos &&
token != "▁") { // Skip SentencePiece space token
scored_tokens.emplace_back(token_scores[id], token);
}
}
}
// Sort by score (descending - higher scores first)
std::sort(scored_tokens.begin(), scored_tokens.end(),
[](const auto& a, const auto& b) { return a.first > b.first; });
Logger::info("Found " + std::to_string(scored_tokens.size()) + " candidate tokens for merge generation");
// Generate merges by finding tokens that can be decomposed into pairs
int merge_rank = 0;
std::unordered_set<std::string> processed_tokens;
for (const auto& [score, token] : scored_tokens) {
if (processed_tokens.count(token)) continue;
// Try to find the best split point for this token
std::string best_left, best_right;
float best_combined_score = -std::numeric_limits<float>::infinity();
// Try all possible split points
for (size_t split = 1; split < token.length(); ++split) {
std::string left = token.substr(0, split);
std::string right = token.substr(split);
// Check if both parts exist in vocabulary
auto left_it = std::find(id_to_token.begin(), id_to_token.end(), left);
auto right_it = std::find(id_to_token.begin(), id_to_token.end(), right);
if (left_it != id_to_token.end() && right_it != id_to_token.end()) {
// Both parts exist, calculate combined score
size_t left_id = std::distance(id_to_token.begin(), left_it);
size_t right_id = std::distance(id_to_token.begin(), right_it);
float left_score = (left_id < token_scores.size()) ?
token_scores[left_id] : 0.0f;
float right_score = (right_id < token_scores.size()) ?
token_scores[right_id] : 0.0f;
float combined_score = left_score + right_score;
if (combined_score > best_combined_score) {
best_combined_score = combined_score;
best_left = left;
best_right = right;
}
}
}
// If we found a valid decomposition, add it as a merge rule
if (!best_left.empty() && !best_right.empty()) {
std::string merge_key = best_left + best_right;
if (generated_merges.find(merge_key) == generated_merges.end()) {
generated_merges[merge_key] = merge_rank++;
Logger::debug("Generated merge: '" + best_left + "' + '" + best_right + "' -> '" + token + "' (rank " + std::to_string(merge_rank-1) + ")");
}
}
processed_tokens.insert(token);
// Limit the number of merges to prevent excessive computation
if (merge_rank >= 50000) {
Logger::info("Reached maximum merge limit (50000), stopping generation");
break;
}
}
Logger::info("Generated " + std::to_string(generated_merges.size()) + " BPE merge rules from vocabulary and scores");
return generated_merges;
}
Tokenizer::Tokenizer(const GGUFData& gguf_data, const ModelConfig& config)
: tokenizer_family_(config.tokenizer_family),
initialized_from_gguf_(true) {
Logger::info("Initializing Tokenizer from GGUFData...");
std::string family_str_gguf = "UNKNOWN";
if (tokenizer_family_ == ModelConfig::TokenizerFamily::LLAMA_SENTENCEPIECE) family_str_gguf = "LLAMA_SENTENCEPIECE";
else if (tokenizer_family_ == ModelConfig::TokenizerFamily::LLAMA3_TIKTOKEN) family_str_gguf = "LLAMA3_TIKTOKEN";
Logger::info(std::string("Tokenizer family from ModelConfig: ") + family_str_gguf);
// Attempt to load chat template from GGUF metadata
try {
auto it = gguf_data.metadata.find("tokenizer.chat_template");
if (it != gguf_data.metadata.end()) {
if (std::holds_alternative<std::string>(it->second)) {
gguf_chat_template_ = std::get<std::string>(it->second);
if (!gguf_chat_template_.empty()) {
Logger::info("[Tokenizer GGUF Init] Found and loaded 'tokenizer.chat_template' from GGUF metadata.");
// Further log the template content if it's not too long, or a snippet
size_t log_len = std::min(gguf_chat_template_.length(), (size_t)70); // Log up to 70 chars
std::string template_snippet = gguf_chat_template_.substr(0, log_len);
if (gguf_chat_template_.length() > log_len) template_snippet += "...";
// Replace newlines with printable \n for one-line logging
std::string loggable_snippet;
for (char ch : template_snippet) {
if (ch == '\n') loggable_snippet += "\\n";
else if (ch == '\r') loggable_snippet += "\\r";
else if (ch == '\t') loggable_snippet += "\\t";
else if (std::isprint(static_cast<unsigned char>(ch))) loggable_snippet += ch;
else loggable_snippet += "."; // Replace non-printable with a dot
}
Logger::debug("[Tokenizer GGUF Init] Chat template snippet: " + loggable_snippet);
} else {
Logger::info("[Tokenizer GGUF Init] 'tokenizer.chat_template' found in GGUF metadata but is empty.");
}
} else {
Logger::warning("[Tokenizer GGUF Init] 'tokenizer.chat_template' found in GGUF metadata but is not a string type.");
}
} else {
Logger::info("[Tokenizer GGUF Init] 'tokenizer.chat_template' not found in GGUF metadata.");
}
} catch (const std::exception& e) {
Logger::error("[Tokenizer GGUF Init] Exception while trying to access 'tokenizer.chat_template': " + std::string(e.what()));
}
if (gguf_data.tokenizer_tokens.empty()) {
throw std::runtime_error(
"GGUF data does not contain 'tokenizer.ggml.tokens'");
}
// Common vocabulary loading
id_to_token_ = gguf_data.tokenizer_tokens;
token_to_id_.clear(); // Ensure map is clear before populating
token_to_id_.reserve(id_to_token_.size());
for (size_t i = 0; i < id_to_token_.size(); ++i) {
token_to_id_[id_to_token_[i]] = static_cast<int>(i);
if (static_cast<int>(i) == 1734) {
const std::string& token_at_1734 = id_to_token_[i];
std::string escaped_token_1734;
for (char c : token_at_1734) {
if (c == '\n') escaped_token_1734 += "\\n";
else if (c == '\r') escaped_token_1734 += "\\r";
else if (c == '\t') escaped_token_1734 += "\\t";
else if (c == '\\') escaped_token_1734 += "\\\\";
else if (std::isprint(static_cast<unsigned char>(c))) escaped_token_1734 += c;
else {
std::stringstream ss_hex;
ss_hex << "<0x" << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(static_cast<unsigned char>(c)) << ">";
escaped_token_1734 += ss_hex.str();
}
}
Logger::info("[GGUF_VOCAB_SCAN] Token string at ID 1734 is: '" + escaped_token_1734 + "' (length: " + std::to_string(token_at_1734.length()) + ")");
}
}
Logger::info("Loaded " + std::to_string(id_to_token_.size()) +
" tokens from GGUF tokenizer_tokens.");
// Log first few tokens for inspection
if (id_to_token_.size() > 0) {
std::string first_few_tokens_log = "First few (up to 10 or vocab size) GGUF tokens: ";
for (size_t i = 0; i < std::min((size_t)10, id_to_token_.size()); ++i) {
first_few_tokens_log += "ID[" + std::to_string(i) + "]='";
// Safely print token, escaping non-printables for logging
for (char c_tok : id_to_token_[i]) {
if (std::isprint(static_cast<unsigned char>(c_tok))) {
first_few_tokens_log += c_tok;
} else {
std::stringstream ss_hex;
ss_hex << "<0x" << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(static_cast<unsigned char>(c_tok)) << ">";
first_few_tokens_log += ss_hex.str();
}
}
first_few_tokens_log += "' ";
}
Logger::info(first_few_tokens_log);
}
// Conditional loading based on family
if (tokenizer_family_ == ModelConfig::TokenizerFamily::LLAMA3_TIKTOKEN) {
type_ = Type::TIKTOKEN_BPE;
Logger::info("Configuring for LLAMA3_TIKTOKEN (gpt2-style BPE).");
if (gguf_data.tokenizer_merges.empty()) {
Logger::warning("Llama 3 Tiktoken family specified, but GGUF data does not contain 'tokenizer.ggml.merges'. Tiktoken BPE may not function correctly without explicit merges.");
} else {
bpe_merges_.clear();
int rank = 0;
// Removed sample_merges vector and related logging logic
for (const std::string& merge_str : gguf_data.tokenizer_merges) {
std::string part1, part2;
size_t space_pos = merge_str.find(' ');
if (space_pos != std::string::npos && space_pos > 0 && space_pos < merge_str.length() - 1) {
part1 = merge_str.substr(0, space_pos);
part2 = merge_str.substr(space_pos + 1);
std::string merged = part1 + part2;
bpe_merges_[merged] = rank++; // Simplified rank assignment
} else {
Logger::warning("Skipping malformed Tiktoken merge rule from GGUF: '" + merge_str + "'");
}
}
Logger::info("Processed " + std::to_string(bpe_merges_.size()) +
" Tiktoken merges from GGUF tokenizer_merges into bpe_merges_ map with ranks.");
}
// Scores are usually not the primary driver for Tiktoken BPE but load if present.
if (!gguf_data.tokenizer_scores.empty()) {
Logger::info("Llama 3 GGUF contains " + std::to_string(gguf_data.tokenizer_scores.size()) + " scores. Loaded.");
token_scores_ = gguf_data.tokenizer_scores;
}
// DEBUGGING: Log vocab/merges for neoplasm
Logger::debug("[DEBUG_VOCAB] LLAMA3_TIKTOKEN bpe_merges_ size: " + std::to_string(bpe_merges_.size()));
std::string target_token_neoplasm = BPE_SPACE_CHAR + "neoplasm"; // "Ġneoplasm"
std::string target_sub_ne = BPE_SPACE_CHAR + "ne"; // "Ġne"
std::string target_sub_o = BPE_SPACE_CHAR + "o"; // "Ġo"
std::string target_sub_oplasm = "oplasm";
std::string target_sub_goplasm = BPE_SPACE_CHAR + "oplasm"; // "Ġoplasm"
auto check_and_log_vocab = [&](const std::string& token_to_check) {
if (token_to_id_.count(token_to_check)) {
Logger::debug("[DEBUG_VOCAB] Found '" + token_to_check + "' in vocab with ID: " + std::to_string(token_to_id_.at(token_to_check)));
} else {
Logger::debug("[DEBUG_VOCAB] Token '" + token_to_check + "' NOT FOUND in vocab.");
}
};
auto check_and_log_merge = [&](const std::string& p1, const std::string& p2) {
auto merge_it = bpe_merges_.find(p1 + p2);
if (merge_it != bpe_merges_.end()) {
Logger::debug("[DEBUG_VOCAB] Found merge for '" + p1 + "' + '" + p2 + "' ('" + (p1+p2) + "') with rank: " + std::to_string(merge_it->second));
} else {
Logger::debug("[DEBUG_VOCAB] Merge for '" + p1 + "' + '" + p2 + "' ('" + (p1+p2) + "') NOT FOUND.");
}
};
} else if (tokenizer_family_ == ModelConfig::TokenizerFamily::LLAMA_SENTENCEPIECE) {
type_ = Type::SENTENCEPIECE_BPE;
Logger::info("Configuring for LLAMA_SENTENCEPIECE.");
if (!gguf_data.tokenizer_scores.empty()) {
token_scores_ = gguf_data.tokenizer_scores;
Logger::info("Loaded " + std::to_string(token_scores_.size()) + " token scores from GGUF for SentencePiece style.");
if (id_to_token_.size() != token_scores_.size()) {
Logger::warning("GGUF (SentencePiece path) token and score array sizes mismatch: tokens=" +
std::to_string(id_to_token_.size()) + ", scores=" + std::to_string(token_scores_.size()));
}
} else {
Logger::warning("SentencePiece family: No scores found. BPE merging will likely not work if no other SP model data is available.");
}
if (!gguf_data.tokenizer_merges.empty()) {
Logger::info("SentencePiece family path: Found 'tokenizer.ggml.merges' in GGUF. Loading them into bpe_merges_ map.");
bpe_merges_.clear();
int rank = 0;
for (const std::string& merge_str : gguf_data.tokenizer_merges) {
std::string part1, part2;
size_t space_pos = merge_str.find(' ');
if (space_pos != std::string::npos && space_pos > 0 && space_pos < merge_str.length() - 1) {
part1 = merge_str.substr(0, space_pos);
part2 = merge_str.substr(space_pos + 1);
bpe_merges_[part1 + part2] = rank++;
} else {
Logger::warning("Skipping malformed SentencePiece merge rule from GGUF: '" + merge_str + "'");
}
}
Logger::info("Processed " + std::to_string(bpe_merges_.size()) +
" merges from GGUF tokenizer_merges into bpe_merges_ map (SentencePiece path).");
} else {
Logger::warning("SentencePiece family path: No 'tokenizer.ggml.merges' found in GGUF. Attempting to generate merges from vocabulary and scores...");
// Generate BPE merges from vocabulary and scores (llama.cpp approach)
auto generated_merges = generate_bpe_merges_from_vocab_scores(id_to_token_, token_scores_);
if (!generated_merges.empty()) {
bpe_merges_ = std::move(generated_merges);
Logger::info("Successfully generated " + std::to_string(bpe_merges_.size()) + " BPE merges from vocabulary and scores for SentencePiece tokenizer");
} else {
Logger::warning("Failed to generate BPE merges. Tokenization may be suboptimal for this model.");
}
}
} else { // UNKNOWN tokenizer family
type_ = Type::UNKNOWN;
Logger::warning("Tokenizer family is UNKNOWN. Tokenizer may not function as expected. Will attempt to load basic vocab and scores if present.");
if (!gguf_data.tokenizer_scores.empty()) {
token_scores_ = gguf_data.tokenizer_scores;
Logger::info("Loaded " + std::to_string(token_scores_.size()) + " token scores from GGUF for UNKNOWN family as a fallback.");
}
}
if (!gguf_data.tokenizer_token_types.empty() && gguf_data.tokenizer_token_types.size() == id_to_token_.size()){
token_types_.resize(gguf_data.tokenizer_token_types.size());
std::transform(gguf_data.tokenizer_token_types.begin(),
gguf_data.tokenizer_token_types.end(), token_types_.begin(),
[](unsigned int u) { return static_cast<int32_t>(u); });
Logger::info("Loaded and transformed " + std::to_string(token_types_.size()) + " token types from GGUF.");
// Populate byte_char_to_id_ and added_tokens_ using token_types_
byte_char_to_id_.clear();
added_tokens_.clear();
id_to_added_token_.clear();
int byte_tokens_from_type = 0;
int special_tokens_from_type = 0;
for (size_t i = 0; i < token_types_.size(); ++i) {
int32_t tt = token_types_[i];
const std::string& token_str = id_to_token_[i];
int token_id = static_cast<int>(i);
bool processed_as_byte = false; // Flag to track if token was handled as byte
if (tt == 6) { // LLAMA_TOKEN_TYPE_BYTE
bool added_byte = false;
if (token_str.length() == 1) {
byte_char_to_id_[token_str[0]] = token_id;
added_byte = true;
} else if (token_str.rfind("<0x", 0) == 0 && token_str.back() == '>' && token_str.length() == 6) {
try {
int byte_val = std::stoi(token_str.substr(3, 2), nullptr, 16);
byte_char_to_id_[static_cast<char>(byte_val)] = token_id;
added_byte = true;
} catch (const std::exception& e) {
Logger::warning("Could not parse byte value from type-BYTE (6) token string: '" + token_str + "'");
}
} else {
// Log if a token is marked as BYTE but doesn't match expected formats
Logger::warning("Token type is BYTE (6) but does not match single char or <0xNN> format: '" + token_str + "' ID: " + std::to_string(token_id));
}
if(added_byte) {
byte_tokens_from_type++;
processed_as_byte = true;
}
}
if (!processed_as_byte && (tt == 2 || tt == 3 || tt == 4 || tt == 5)) {
if (added_tokens_.find(token_str) == added_tokens_.end()) {
added_tokens_[token_str] = token_id;
id_to_added_token_[token_id] = token_str;
special_tokens_from_type++;
}
}
}
// Log message now reflects bytes identified from type 6 tokens
Logger::info("From GGUF token_types (BYTE=6): Identified " + std::to_string(byte_tokens_from_type) + " byte tokens (for byte_char_to_id_). " +
"Identified " + std::to_string(special_tokens_from_type) + " other special/added tokens (types 2,3,4,5).");
// If token types were processed but yielded no byte tokens for Tiktoken, try the fallback vocab scan.
if (tokenizer_family_ == ModelConfig::TokenizerFamily::LLAMA3_TIKTOKEN && byte_tokens_from_type == 0) {
Logger::warning("No byte tokens identified via token_types metadata for Tiktoken. Attempting fallback scan of vocabulary.");
// Manually populate byte_char_to_id_ by checking vocab for <0xNN> and literal byte strings
byte_char_to_id_.clear(); // Clear again in case some non-byte type 3 were added incorrectly before
int bytes_found_in_vocab_fallback = 0;
for (int i = 0; i < 256; ++i) {
std::stringstream ss_hex_repr;
ss_hex_repr << "<0x" << std::hex << std::setw(2) << std::setfill('0') << i << ">";
std::string byte_token_str_repr = ss_hex_repr.str();
std::string literal_byte_char_str(1, static_cast<char>(i));
bool is_space_char = (static_cast<char>(i) == ' ');
if (is_space_char) {
Logger::debug("[BYTE_FALLBACK_DEBUG] Checking for SPACE (byte 32). Looking for '<0x20>' and ' '.");
}
auto it = token_to_id_.find(byte_token_str_repr);
if (it != token_to_id_.end()) {
if (is_space_char) {
Logger::debug("[BYTE_FALLBACK_DEBUG] Found '<0x20>' token with ID: " + std::to_string(it->second) + ". Adding to map.");
}
byte_char_to_id_[static_cast<char>(i)] = it->second;
bytes_found_in_vocab_fallback++;
} else {
// Also check for literal single-byte characters if they are printable
if (std::isprint(static_cast<unsigned char>(i))) {
auto lit_it = token_to_id_.find(literal_byte_char_str);
if (lit_it != token_to_id_.end()) {
if (is_space_char) {
Logger::debug("[BYTE_FALLBACK_DEBUG] Did not find '<0x20>', but found literal ' ' token with ID: " + std::to_string(lit_it->second));
}
// Ensure this token ID hasn't already been mapped (e.g., by a <0xNN> entry)
bool id_already_mapped = false;
for(const auto& pair : byte_char_to_id_) { if (pair.second == lit_it->second) { id_already_mapped = true; break; } }
if (!id_already_mapped) {
if (is_space_char) {
Logger::debug("[BYTE_FALLBACK_DEBUG] ID " + std::to_string(lit_it->second) + " for ' ' not already mapped. Adding to map.");
}
byte_char_to_id_[static_cast<char>(i)] = lit_it->second;
bytes_found_in_vocab_fallback++;
// Don't need a continue here, just prevents double-counting if somehow both exist
} else {
if (is_space_char) {
Logger::debug("[BYTE_FALLBACK_DEBUG] ID " + std::to_string(lit_it->second) + " for ' ' was already mapped (likely by <0x20>). Skipping literal add.");
}
}
} else {
if (is_space_char) {
Logger::debug("[BYTE_FALLBACK_DEBUG] Did not find '<0x20>' OR literal ' ' token in vocab.");
}
}
} else {
if (is_space_char) {
Logger::debug("[BYTE_FALLBACK_DEBUG] Did not find '<0x20>' token, and space is not printable, so didn't check for literal ' '.");
}
}
}
}
Logger::info("Fallback byte_char_to_id_ map population: Found representations for " + std::to_string(bytes_found_in_vocab_fallback) +
" byte values in GGUF vocab (using <0xNN> or literal). Intended for Tiktoken BPE.");
byte_tokens_from_type = bytes_found_in_vocab_fallback;
}
} else {
Logger::warning("GGUF tokenizer_token_types array missing or size mismatch. Byte token and special token identification will be limited.");
if (tokenizer_family_ == ModelConfig::TokenizerFamily::LLAMA3_TIKTOKEN) {
byte_char_to_id_.clear();
int bytes_found_in_vocab_fallback = 0;
for (int i = 0; i < 256; ++i) {
std::stringstream ss_hex_repr;
ss_hex_repr << "<0x" << std::hex << std::setw(2) << std::setfill('0') << i << ">";
std::string byte_token_str_repr = ss_hex_repr.str();
std::string literal_byte_char_str(1, static_cast<char>(i));
bool is_space_char = (static_cast<char>(i) == ' ');
if (is_space_char) {
Logger::debug("[BYTE_FALLBACK_DEBUG] Checking for SPACE (byte 32). Looking for '<0x20>' and ' '.");
}
auto it = token_to_id_.find(byte_token_str_repr);
if (it != token_to_id_.end()) {
if (is_space_char) {
Logger::debug("[BYTE_FALLBACK_DEBUG] Found '<0x20>' token with ID: " + std::to_string(it->second) + ". Adding to map.");
}
byte_char_to_id_[static_cast<char>(i)] = it->second;
bytes_found_in_vocab_fallback++;
} else {
// Also check for literal single-byte characters if they are printable
if (std::isprint(static_cast<unsigned char>(i))) {
auto lit_it = token_to_id_.find(literal_byte_char_str);
if (lit_it != token_to_id_.end()) {
if (is_space_char) {
Logger::debug("[BYTE_FALLBACK_DEBUG] Did not find '<0x20>', but found literal ' ' token with ID: " + std::to_string(lit_it->second));
}
// Ensure this token ID hasn't already been mapped (e.g., by a <0xNN> entry)
bool id_already_mapped = false;
for(const auto& pair : byte_char_to_id_) { if (pair.second == lit_it->second) { id_already_mapped = true; break; } }
if (!id_already_mapped) {
if (is_space_char) {
Logger::debug("[BYTE_FALLBACK_DEBUG] ID " + std::to_string(lit_it->second) + " for ' ' not already mapped. Adding to map.");
}
byte_char_to_id_[static_cast<char>(i)] = lit_it->second;
bytes_found_in_vocab_fallback++;
continue;
} else {
if (is_space_char) {
Logger::debug("[BYTE_FALLBACK_DEBUG] ID " + std::to_string(lit_it->second) + " for ' ' was already mapped (likely by <0x20>). Skipping literal add.");
}
}
} else {
if (is_space_char) {
Logger::debug("[BYTE_FALLBACK_DEBUG] Did not find '<0x20>' OR literal ' ' token in vocab.");
}
}
} else {
if (is_space_char) {
Logger::debug("[BYTE_FALLBACK_DEBUG] Did not find '<0x20>' token, and space is not printable, so didn't check for literal ' '.");
}
}
}
}
Logger::info("Fallback byte_char_to_id_ map population: Found representations for " + std::to_string(bytes_found_in_vocab_fallback) +
" byte values in GGUF vocab (using <0xNN> or literal). Intended for Tiktoken BPE.");
}
}
if (byte_char_to_id_.find(' ') == byte_char_to_id_.end()) {
Logger::info("[GENERAL_BYTE_FALLBACK] Space ' ' not found in byte_char_to_id_. Attempting to populate from vocab.");
int general_fallback_bytes_added = 0;
for (int i = 0; i < 256; ++i) {
char current_char = static_cast<char>(i);
// Only add if not already present from a more primary source (like token_types)
if (byte_char_to_id_.count(current_char)) {
continue;
}
std::stringstream ss_hex_repr;
ss_hex_repr << "<0x" << std::hex << std::setw(2) << std::setfill('0') << i << ">";
std::string byte_token_str_repr = ss_hex_repr.str();
std::string literal_byte_char_str(1, current_char);
auto it_hex = token_to_id_.find(byte_token_str_repr);
if (it_hex != token_to_id_.end()) {
byte_char_to_id_[current_char] = it_hex->second;
general_fallback_bytes_added++;
if (current_char == ' ') Logger::debug("[GENERAL_BYTE_FALLBACK] Found space as '" + byte_token_str_repr + "' -> ID: " + std::to_string(it_hex->second));
} else {
auto it_lit = token_to_id_.find(literal_byte_char_str);
if (it_lit != token_to_id_.end()) {
byte_char_to_id_[current_char] = it_lit->second;
general_fallback_bytes_added++;
if (current_char == ' ') Logger::debug("[GENERAL_BYTE_FALLBACK] Found space as literal '" + literal_byte_char_str + "' -> ID: " + std::to_string(it_lit->second));
}
}
}
Logger::info("[GENERAL_BYTE_FALLBACK] Added " + std::to_string(general_fallback_bytes_added) +
" new entries to byte_char_to_id_ map. Final size: " + std::to_string(byte_char_to_id_.size()));
if (byte_char_to_id_.find(' ') == byte_char_to_id_.end()) {
Logger::warning("[GENERAL_BYTE_FALLBACK] Space ' ' still not found in byte_char_to_id_ after fallback scan!");
}
if (byte_char_to_id_.find(' ') == byte_char_to_id_.end()) { // Check again if space wasn't found by hex/literal
const std::string sp_space_token = "\xE2\x96\x81"; // U+2581
auto it_sp_space = token_to_id_.find(sp_space_token);
if (it_sp_space != token_to_id_.end()) {
byte_char_to_id_[' '] = it_sp_space->second; // Map standard space char to the ID of the SP space token
Logger::info("[GENERAL_BYTE_FALLBACK] SUCCESS: Found SentencePiece space token '" + sp_space_token +
"' (ID: " + std::to_string(it_sp_space->second) + "). Mapped standard space ' ' to this ID.");
} else {
// This is the final warning if space still not found
Logger::warning("[GENERAL_BYTE_FALLBACK] Space ' ' still not found in byte_char_to_id_ after fallback scan AND specific SP space check!");
}
}
}
bos_token_id_ = config.bos_token_id;
eos_token_id_ = config.eos_token_id;
unk_token_id_ = config.unk_token_id;
pad_token_id_ = config.pad_token_id;
// Ensure UNK token ID is valid (non-negative). Default to 0 if invalid.
if (unk_token_id_ < 0) {