Map raw bytes to printable characters for byte-level BPE

Why it matters GPT-2 style tokenizers use this byte to character table, which is why their vocab files show a G-with-dot symbol at the start of words.

Byte-level BPE works on the 256 possible bytes, but merge tables are stored as text, so every byte is first mapped to a visible Unicode character. Spaces become a visible marker.

Write byte_level_encode(text). Build a table for bytes 0 to 255: bytes 33 to 126, 161 to 172 and 174 to 255 map to the character with the same code point. The remaining bytes, in increasing order, map to chr(256), chr(257), chr(258) and so on. Encode text as UTF-8 and return the string of mapped characters.

Signaturedef byte_level_encode(text)

Example

byte_level_encode("hi there") is "hi\u0120there" (the space, byte 32, is the 33rd remapped byte, so it becomes chr(288)).

Understand the idea

Byte-level BPE can tokenize any text because it starts from the 256 possible bytes, so nothing is ever unknown. The catch is that some bytes are invisible (space, newline, control codes), and merge files are plain text. The fix is a fixed table that gives every byte a visible stand-in character, like giving every guest a name badge.

Bytes that already print nicely (33 to 126, 161 to 172, 174 to 255) keep their own character. The other 68 bytes are numbered in order from 256. Byte 0 becomes chr(256), ..., byte 10 (newline) becomes chr(266), byte 32 (space) becomes chr(288), which looks like a capital G with a dot.

Example: "hi there" has bytes h, i, 32, t, h, e, r, e, which map to "hi" + chr(288) + "there".

Rule: mapped = [table[b] for b in text.encode("utf-8")].

GPT-2 and many later tokenizers use this table, so their vocab files show that dotted G at the start of tokens that begin with a space.

Shapes and data flow

text -> UTF-8 bytes (n,) -> n printable characters
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplebyte_level_encode('hi there')
  • Sample 2: newlinebyte_level_encode('a\nb')
  • Test 3: accentbyte_level_encode('caf\u00e9')
  • Test 4: emoji byteslen(byte_level_encode('\U0001F600'))