Forward GPT-2 byte encoding: raw byte → Unicode codepoint (UTF-8 string). This is the inverse of gpt2_unicode_to_byte (defined later, near decode). Bytes in {33-126, 161-172, 174-255} map to themselves as a codepoint; all others (0-32, 127-160, 173) map to U+0100..U+0143.
| 315 | // Bytes in {33-126, 161-172, 174-255} map to themselves as a codepoint; |
| 316 | // all others (0-32, 127-160, 173) map to U+0100..U+0143. |
| 317 | static std::string byte_to_gpt2_unicode(uint8_t b) { |
| 318 | // Build forward table once (thread-safe via C++11 static init). |
| 319 | static const auto fwd = []() { |
| 320 | std::array<uint32_t, 256> t{}; |
| 321 | int n = 0; |
| 322 | for (int i = 0; i < 256; i++) { |
| 323 | if ((i >= 33 && i <= 126) || |
| 324 | (i >= 161 && i <= 172) || |
| 325 | (i >= 174 && i <= 255)) { |
| 326 | t[i] = (uint32_t)i; |
| 327 | } else { |
| 328 | t[i] = 256 + n; |
| 329 | n++; |
| 330 | } |
| 331 | } |
| 332 | return t; |
| 333 | }(); |
| 334 | uint32_t cp = fwd[b]; |
| 335 | // Encode codepoint as UTF-8. |
| 336 | char buf[4]; |
| 337 | int len; |
| 338 | if (cp < 0x80) { |
| 339 | buf[0] = (char)cp; len = 1; |
| 340 | } else if (cp < 0x800) { |
| 341 | buf[0] = (char)(0xC0 | (cp >> 6)); |
| 342 | buf[1] = (char)(0x80 | (cp & 0x3F)); |
| 343 | len = 2; |
| 344 | } else { |
| 345 | buf[0] = (char)(0xE0 | (cp >> 12)); |
| 346 | buf[1] = (char)(0x80 | ((cp >> 6) & 0x3F)); |
| 347 | buf[2] = (char)(0x80 | (cp & 0x3F)); |
| 348 | len = 3; |
| 349 | } |
| 350 | return std::string(buf, len); |
| 351 | } |
| 352 | |
| 353 | // Convert a raw UTF-8 text piece to GPT-2 byte-encoded form for BPE lookup. |
| 354 | static std::string encode_gpt2_bpe(const std::string & text) { |
no outgoing calls
no test coverage detected