| 167 | } |
| 168 | |
| 169 | std::pair<std::vector<int>, int> CoreBPE::encode(const std::string& text, const emhash8::HashSet<std::string>& allowed_special) { |
| 170 | std::vector<int> result; |
| 171 | result.reserve(text.length()); |
| 172 | |
| 173 | // Validate that all allowed_special tokens exist in special_encoder |
| 174 | // also initialize the next_special_cache with -1. |
| 175 | emhash8::HashMap<std::string, int> next_special_cache; |
| 176 | next_special_cache.reserve(allowed_special.size()); |
| 177 | for (const auto& special_token : allowed_special) { |
| 178 | if (special_encoder.find(special_token) == special_encoder.end()) { |
| 179 | throw TiktokenError("Special token '" + special_token + "' not found in special encoder"); |
| 180 | } |
| 181 | next_special_cache.emplace_unique(special_token, -1); |
| 182 | } |
| 183 | |
| 184 | int start = 0; |
| 185 | int last_piece_token_len = 0; // number of tokens in the last piece (i.e. last regex match). |
| 186 | std::string next_special_token; |
| 187 | while (true) { |
| 188 | // find the next allowed special token. |
| 189 | next_special_token = ""; |
| 190 | int next_special_token_pos = -1; |
| 191 | int start_offset = start; |
| 192 | while (true) { |
| 193 | auto [pos, token] = find_next_special_token(text, start_offset, next_special_cache); |
| 194 | if (pos == std::string::npos) { // not found, no more special tokens. |
| 195 | break; |
| 196 | } |
| 197 | // found an allowed special token. |
| 198 | next_special_token = token; |
| 199 | next_special_token_pos = pos; |
| 200 | break; |
| 201 | } |
| 202 | int end = next_special_token_pos == -1 ? text.length() : next_special_token_pos; |
| 203 | |
| 204 | // now process the text normally, up until the found special token (or the end of the text). |
| 205 | auto pieces = split_text(text, start, end); |
| 206 | int prev_result_size = result.size(); |
| 207 | for (const auto& piece : pieces) { |
| 208 | prev_result_size = result.size(); |
| 209 | std::vector<unsigned char> bytes(piece.begin(), piece.end()); |
| 210 | auto it = encoder.find(bytes); |
| 211 | if (it != encoder.end()) { |
| 212 | result.push_back(it->second); |
| 213 | last_piece_token_len = 1; |
| 214 | continue; |
| 215 | } |
| 216 | byte_pair_encode(bytes, encoder, result); |
| 217 | } |
| 218 | last_piece_token_len = result.size() - prev_result_size; |
| 219 | |
| 220 | // encode the special token. |
| 221 | if (next_special_token != "") { |
| 222 | result.push_back(special_encoder.at(next_special_token)); |
| 223 | // update the start position. |
| 224 | start = end + next_special_token.length(); |
| 225 | last_piece_token_len = 0; |
| 226 | } else { |
no test coverage detected