| 55 | } |
| 56 | |
| 57 | std::vector<int> Tokenizer::encode(const std::string& text, bool encode_bos) const { |
| 58 | std::vector<int> out_tokens; |
| 59 | if (encode_bos) { |
| 60 | out_tokens.push_back(bos_id); |
| 61 | } |
| 62 | |
| 63 | for (size_t i = 0; i < text.size();) { |
| 64 | size_t l = 0; |
| 65 | size_t valid_l = 0; |
| 66 | const TokenTrie* p = &vocab_trie; |
| 67 | const TokenTrie* valid_p = nullptr; |
| 68 | while (i + l < text.size()) { |
| 69 | char c = text[i+l]; |
| 70 | if (p->children.count(c)) { |
| 71 | p = p->children.at(c).get(); |
| 72 | l += 1; |
| 73 | if (p->token_id >= 0) { |
| 74 | valid_p = p; |
| 75 | valid_l = l; |
| 76 | } |
| 77 | } else { |
| 78 | break; |
| 79 | } |
| 80 | } |
| 81 | if (!valid_p) { |
| 82 | // No substring starting from `i` matches any vocab words, use byte fallback |
| 83 | if (byte_fallback_start >= 0) { |
| 84 | out_tokens.push_back((unsigned char)text[i] + byte_fallback_start); |
| 85 | } |
| 86 | i += 1; |
| 87 | } else { |
| 88 | out_tokens.push_back(valid_p->token_id); |
| 89 | i += valid_l; |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | return out_tokens; |
| 94 | } |
| 95 | |
| 96 | std::string Tokenizer::encoding_to_debug_string(const std::vector<int>& encoding) const { |
| 97 | std::string token_encoding_debug_str = ""; |
no outgoing calls
no test coverage detected