11.2 Injective, surjective, bijective: the GPT-2 byte map
Until the tokenizers chapter of AI Engineering, the system’s tokenizer is the simplest possible one: one token per byte, vocabulary 256. Byte-level BPE replaces it, and the first thing that section does is load a real vocabulary, SmolLM2’s tokenizer.json. Open it and the tokens look wrong: "Ġthe", "Ċ", "ĠĠĠ". There is no " the" anywhere. A loader that reads those keys as text finds no token that starts with a space, so every word after the first gets split into single bytes and the ids stop matching the model’s.
Concepts from other sections (5)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Bijection: a function that is both injective and surjective, and so has an inverse. Read more: 11.3.4 Relations, functions, and validation
- Code point: one element of a Python
str; a Unicode scalar between U+0000 and U+10FFFF. Read more: 7.1 The tokenizer protocol and the char tokenizer in AI Engineering - Byte-level: the base alphabet is the 256 bytes (through the byte map), so every text encodes and there is no unknown token. Read more: 7.2 Byte-level BPE in AI Engineering
- Fixed point: a value with . Read more: 15.5 Fixed-point iteration and fast inverse square root in C
- Control byte: one byte per slot holding EMPTY, DELETED, or the key’s 7-bit fingerprint. Read more: 15.2 A Swiss table in Programming and Algorithms
The fix is a fixed bijection between the 256 byte values and 256 visible characters, the one GPT-2 introduced. This section derives that bijection, together with the three definitions (injective, surjective, bijective) that prove it can be inverted. It is a small piece of discrete math with an unusually concrete payoff: get one range boundary wrong and no real vocabulary loads.
No code from earlier sections is needed; the functions and bijections problems in this chapter’s problem set are good preparation. The solution is bytes_unicode.py, with is_injective, is_surjective, inverse, bytes_to_unicode, unicode_to_bytes, encode_bytes, and decode_chars; the typed interface is course/contracts/py/tinyllm/tok/bytes_unicode.pyi.
Learning objectives
- Decide whether a finite function is injective, surjective onto a given codomain, or bijective, and say exactly what each check inspects.
- Use the counting argument to show that between finite sets of equal size the three properties coincide.
- Derive GPT-2’s byte-to-character table from its rule and encode a sentence by hand.
- Implement an inverse that refuses to hide collisions, and a decoder that rejects characters outside the image.
Notation
Section titled “Notation”The section uses these symbols and their Python counterparts:
| Symbol | Meaning | Type / shape |
|---|---|---|
| , | finite sets: the domain (inputs) and the codomain (allowed outputs) | set |
| a function: exactly one output for every | Mapping (keys ) | |
| the image: the outputs that actually occur | set | |
| the number of elements of | int | |
| the inverse of a bijection: and | dict | |
| a byte value | int | |
| how many bytes before were remapped (the running count) | int | |
| , | code point to its one-character string, and back | str, int |
Functions as tables
Section titled “Functions as tables”A function assigns one output to every input. When is finite it can be written down as a table, and a Python dict is exactly that: its keys are and its values are the outputs. A dict cannot give one key two values, so every dict is a function from its key set. The codomain is not stored anywhere; it is part of the question being asked.
Injective, surjective, bijective
Section titled “Injective, surjective, bijective”With functions as tables, each of the three properties becomes a check on the table.
is injective (one to one) when different inputs give different outputs: . Equivalently, no value appears twice. Notice what is checked: the values. The keys of a dict are always distinct, so checking them proves nothing.
is surjective onto when every is some , that is, . This is a statement about , so it needs . If some lies outside , then is not a function into at all, and is_surjective raises instead of answering.
is bijective when it is both. Then every has exactly one preimage, and , defined as that preimage, is a function . If is not injective, two keys compete for . A dict comprehension {v: k for k, v in f.items()} silently keeps the last one, which is why inverse must check and raise.
Counting settles it for equal sizes
Section titled “Counting settles it for equal sizes”For finite sets there is a shortcut. If is injective, its image has exactly elements, one per input. So when , an injective hits all of and is also surjective. Conversely, a surjective needs at least distinct outputs, which uses up all inputs with no repeats; that is the pigeonhole principle, which the problem set practices. For finite sets of equal size the three properties coincide: 256 bytes with 256 distinct outputs is a bijection onto those 256 outputs.
Why GPT-2 needs a byte map
Section titled “Why GPT-2 needs a byte map”Byte-level BPE works on bytes, so its tokens are byte strings: b" the", b"\n", and halves of UTF-8 characters such as b"\xc3". Three places need them as text, and each rules out a different set of characters:
vocab.jsonandtokenizer.jsonare JSON, whose keys must be valid Unicode text. A lone byte0xC3is not valid UTF-8, so a raw byte string cannot be a key.merges.txtstores one merge per line as two tokens separated by a space (Ġ t). A token that contains a space would split the line in the wrong place.- Control characters (
0x00to0x1F) and the soft hyphen0xADare invisible, so a vocabulary full of them cannot be read or diffed.
So GPT-2 maps each byte to a character that is printable and not whitespace, by a fixed rule.
The rule
Section titled “The rule”Latin-1 gives every byte the character , and 188 of those are already visible: ! to ~ (0x21 to 0x7E, 94 characters), ¡ to ¬ (0xA1 to 0xAC, 12), and ® to ÿ (0xAE to 0xFF, 82). Those keep their own code point. The other bytes (0x00 to 0x20, 0x7F to 0xA0, and 0xAD) are walked in increasing order, and the -th of them () gets , the code points U+0100 to U+0143. Those are Latin Extended-A letters such as Ā, Ġ, Ń, all visible.
The map is injective because the kept bytes land in (each on itself, so distinct) and the remapped bytes land in (each on a new , so distinct), and the two ranges do not overlap. By the counting argument it is a bijection onto its 256-character image, so unicode_to_bytes exists. The image is not “all characters”, though: a real space " " or "ń" (U+0144) is not the image of any byte, and decode_chars must reject them.
Encoding and decoding then follow. encode_bytes(data) replaces each byte by its character, so the output has exactly len(data) characters. decode_chars(text) applies the inverse character by character. Composing them in either order is the identity, for any bytes, including invalid UTF-8.
Working it by hand
Section titled “Working it by hand”Start with three small maps. Take and . The four questions below exercise each definition:
| Question | Work | Answer |
|---|---|---|
| is injective? | with | no; inverse(f) raises, naming a |
| is injective? | values are distinct | yes |
| is onto ? | image equals it | yes, so |
| is onto ? | has no preimage | no |
Now the byte map. Where the space goes: bytes 0x00 to 0x20 are all remapped (the first kept byte is 0x21 !), and they come first, so byte has . The space 0x20 = 32 has and maps to $\mathrm{chr}(256 + 32) = $ U+0120 Ġ. The newline 0x0A has and maps to U+010A Ċ. Byte 0x00 maps to U+0100 Ā.
Past the gap: DEL, 0x7F, is the first remapped byte after ~. Before it come 33 remapped bytes (0x00 to 0x20), so and it maps to U+0121 ġ. The soft hyphen 0xAD comes after 0x7F to 0xA0 (34 more), so , the last one: U+0143 Ń.
A sentence: "Hi there\n" is the bytes 48 69 20 74 68 65 72 65 0A, which map as follows:
| byte | 48 | 69 | 20 | 74 | 68 | 65 | 72 | 65 | 0A |
|---|---|---|---|---|---|---|---|---|---|
| kept? | H | i | no, | t | h | e | r | e | no, |
| char | H | i | Ġ | t | h | e | r | e | Ċ |
So encode_bytes(b"Hi there\n") == "HiĠthereĊ", nine bytes to nine characters, and in a GPT-2 vocabulary the word ” there” (with its leading space) is the token "Ġthere".
A non-ASCII character: "é" is the two UTF-8 bytes C3 A9. Both are kept Latin-1 characters, à and ©, so it encodes to "é": two characters, the familiar look of mis-decoded UTF-8.
These examples are the first two test cases below.
Designing the interface
Section titled “Designing the interface”Seven functions, three for the definitions and four for the byte map:
def is_injective(f: Mapping[K, V]) -> booldef is_surjective(f: Mapping[K, V], codomain: Iterable[V]) -> bool # ValueError if a value is outsidedef inverse(f: Mapping[K, V]) -> dict[V, K] # ValueError if not injectivedef bytes_to_unicode() -> dict[int, str] # a new dict each call, keys 0..255 in orderdef unicode_to_bytes() -> dict[str, int]def encode_bytes(data: bytes) -> str # TypeError for strdef decode_chars(text: str) -> bytes # ValueError outside the imageThe solution builds bytes_to_unicode from the rule, not by pasting a table. A correct table equals GPT-2’s entry for entry, and the rule is what the Rust fast BPE reimplements.
A correct solution must handle these cases:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| Hand example, encode | unit | "Hi there\n" encodes to "HiĠthereĊ"; byte 0 is Ā; decode inverts it | pins the rule |
| Hand example, small maps | unit | and of the worked example | the three definitions, on paper and in code |
| GPT-2’s table | golden | all 256 entries equal the transformers table | byte-level BPE loads GPT-2 and SmolLM2 vocabularies |
| Bijection onto 256 characters | property | 256 keys, 256 distinct one-character values | lossless bytes to text and back |
| Printable, not whitespace | property | no output is a space, control, or invisible character | merges files split on spaces |
| Kept bytes are fixed points | unit | the 188 kept bytes are fixed points; 0xAD is not | ASCII tokens read as themselves |
| Remapped bytes consecutive from 256 | unit | the 68 others take U+0100 to U+0143 in order | the running count, not the byte value |
| Byte order, fresh dict | boundary | a caller’s edit does not leak into the next call | tokenizers build their own tables from it |
| The inverse | property | both compositions are the identity | decoding generated tokens |
| Random bytes round trip | property | decode(encode(x)) == x for random bytes | tokens can end inside a UTF-8 character |
| UTF-8 text round trip | unit | é is two characters, the emoji four | the map works on bytes, not characters |
| Characters outside the image | boundary | " ", "\n", U+0144, € raise | a corrupt vocabulary fails loudly |
A str passed to encode | boundary | encode_bytes("abc") is a TypeError | forgetting .encode("utf-8") is a bug |
| Inverse of a collision | boundary | a repeated value raises and names it | two ids never share a string |
| Injective cases | unit | empty, identity, permutation, collisions | injectivity is about values |
| Surjective cases | boundary | empty codomain, missing targets, values outside | surjectivity needs a codomain |
Building it step by step
Section titled “Building it step by step”Six steps take you from the definitions to the code.
- A finite function is a dict, and its keys are distinct by construction. So injectivity is a question about the values only: scan them once and stop at the first repeat.
- Surjectivity needs the codomain as an argument, and it only makes sense for a function into that codomain. So the solution first checks that the image lies inside the codomain (raising otherwise), and then compares the image with the codomain as sets.
- An inverse exists only for an injective map, and a dict comprehension would hide a collision. So
inversebuilds the dict one pair at a time and raises the moment a value is seen twice, naming both keys. - The byte map must be GPT-2’s exactly, so it is built from GPT-2’s rule: three kept ranges, then the 68 other bytes in increasing order, each taking the next code point from 256. The counter is the running count of remapped bytes, not the byte value.
- Injectivity of that map follows from the two disjoint output ranges, and equal sizes make it a bijection. So
unicode_to_bytesis simplyinverseof the table, andinversere-checks the claim at run time. - Encoding and decoding are the table and its inverse applied character by character. Decoding must reject anything outside the 256-character image instead of computing a byte by arithmetic.
The three definitions come first. is_injective looks only at values; is_surjective checks “into” before “onto”:
def is_injective(f: Mapping[Hashable, Hashable]) -> bool: seen: set = set() for v in f.values(): # the values, never the keys: keys are always distinct if v in seen: return False # two inputs share an output seen.add(v) return True
def is_surjective(f: Mapping[Hashable, Hashable], codomain: Iterable[Hashable]) -> bool: target = set(codomain) image = set(f.values()) outside = image - target if outside: # f is not a function into B: the question has no answer raise ValueError( f"f is not a function into the codomain: value {next(iter(outside))!r} is outside it" ) return image == target # equality, not image <= target: every b must be hitinverse is the only safe way to flip a dict, because it refuses to overwrite:
def inverse(f: Mapping[Hashable, Hashable]) -> dict: inv: dict = {} for k, v in f.items(): if v in inv: # a second preimage for v: f is not injective raise ValueError( f"f is not injective: keys {inv[v]!r} and {k!r} both map to {v!r}" ) inv[v] = k return invThe byte map is the rule, line for line. The kept set is written as three inclusive ranges; the gap at 0xAD is what splits the last two:
def bytes_to_unicode() -> dict[int, str]: # The printable Latin-1 ranges keep their own code point. 0xAD (soft # hyphen) sits between the last two and is invisible, so it is remapped. ranges = ((0x21, 0x7E), (0xA1, 0xAC), (0xAE, 0xFF)) keep = {b for lo, hi in ranges for b in range(lo, hi + 1)} # 94 + 12 + 82 = 188 out: dict[int, str] = {} n = 0 # how many bytes have been remapped so far for b in range(256): # increasing byte order: keys come out 0..255 if b in keep: out[b] = chr(b) # visible already: a fixed point else: out[b] = chr(256 + n) # the n-th invisible byte -> U+0100 + n n += 1 return out # a new dict on every call: callers may edit theirsTracing it reproduces the worked example: bytes 0 to 32 are the first 33 remapped (space is , Ġ), DEL gets , and the soft hyphen is last with , Ń.
unicode_to_bytes reuses inverse, so the bijection is checked, not assumed. Encoding refuses str, because a str would have to be encoded to bytes first, and guessing Latin-1 is wrong past U+00FF. Decoding refuses characters outside the image:
def unicode_to_bytes() -> dict[str, int]: return inverse(bytes_to_unicode())
def encode_bytes(data: bytes) -> str: if not isinstance(data, (bytes, bytearray)): raise TypeError(f"encode_bytes takes bytes, got {type(data).__name__}") table = bytes_to_unicode() return "".join(table[b] for b in data) # one character per byte
def decode_chars(text: str) -> bytes: table = unicode_to_bytes() out = bytearray() for i, ch in enumerate(text): b = table.get(ch) # a lookup, never ord(ch) - 256 if b is None: # " ", "\n", U+0144, "€": not an image raise ValueError( f"character {ch!r} (U+{ord(ch):04X}) at index {i} is not in the byte map's image" ) out.append(b) return bytes(out)The full solution is in bytes_unicode.py.
Why this design
Section titled “Why this design”On cost: is_injective, is_surjective, and inverse are with set and dict lookups. bytes_to_unicode is 256 steps. encode_bytes and decode_chars are linear in their input plus a rebuild of the 256-entry table on every call. That constant is negligible next to tokenization, and it buys a table no caller can corrupt.
The table is built from the rule rather than pasted because a pasted table of 256 entries is easy to get subtly wrong and impossible to read. The rule is three ranges and a counter, matches GPT-2’s original bytes_to_unicode, and is what the Rust tokenizer reimplements.
Decoding uses a lookup, not arithmetic, because ord(c) - 256 is right only for the first 33 remapped bytes; after DEL the remapped code points no longer equal . Arithmetic also turns characters outside the image into some byte instead of an error, so a corrupt vocabulary would decode to garbage silently.
The table is not cached in a module global because a shared dict lets one caller’s mutation change every later tokenizer, and returning a fresh dict costs microseconds. (Production code builds it once and freezes it; see the further reading.)
One tradeoff is accepted: is_surjective raises instead of returning False for a map that is not into . That is stricter than a boolean, but “onto ” is not a meaningful question for such a map, and a silent False would hide a caller’s bug.
What can go wrong
Section titled “What can go wrong”Several of these mistakes still produce a valid bijection, just not GPT-2’s, which is why the golden comparison against the real table matters:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
mapping every byte to itself, chr(b) | a bijection, but the space and control bytes stay invisible; merges lines split inside tokens | remaps every byte outside the three kept ranges |
| one range 0xA1 to 0xFF | the soft hyphen 0xAD keeps its invisible code point and every later remapped byte is off | three ranges, with 0xAD left out between them |
remapping to chr(256 + b) | still injective and visible, but not GPT-2’s table: no real vocabulary loads | chr(256 + n) with the running count (step 4) |
decoding by arithmetic (ord(c) - 256, & 0xFF) | happens to work for bytes 0 to 32, decodes everything after DEL to the wrong byte, and accepts characters outside the image | decodes by looking up unicode_to_bytes() and raises on a miss |
| inverting with a dict comprehension | a collision keeps the last key silently; two ids share one string | inverse raises on the first repeated value |
| checking keys for injectivity | always true, since dict keys are distinct | scans f.values() |
| “onto” as | a map that misses targets reports onto | returns image == target |
| ignoring values outside the codomain | the question “onto ?” answered for a map that is not into | raises when image - target is not empty |
| caching the table in a module global | one caller’s edit changes every later tokenizer | builds and returns a new dict on every call |
encoding a str by code points | "é" becomes one byte, wrong for anything past Latin-1 | encode_bytes raises TypeError unless given bytes or bytearray |
an off-by-one range end (0x7E vs 0x7D) | ~ is remapped | the first range is (0x21, 0x7E), inclusive |
Warning:
ord(c) - 256passes every test on ASCII text with spaces and newlines, because those bytes are all below DEL. It fails only on the bytes after the gap, which is exactly where UTF-8 continuation bytes live.
Where this leads
Section titled “Where this leads”The functions, inverses, and pigeonhole problems in this chapter’s problem set are the pen-and-paper side of this section. In AI Engineering, the byte map is used throughout the tokenizer and decoding code:
- The tokenizer protocol and the char tokenizer: every byte-level tokenizer decodes ids through
decode_chars. - Byte-level BPE: pre-tokenized text is encoded to UTF-8, mapped with
encode_bytes, merged, and looked up invocab.json; the Hugging Face loader readsĠ-keys withunicode_to_bytes. - Rust fast BPE:
tl-tokrebuilds the same table from the same rule (a reimplementation, not a call) and is tested id for id against byte-level BPE. - Constrained decoding undoes the byte map with
unicode_to_bytesto recover each token’s bytes before walking them through a DFA. - Whisper decoding and long-form transcription consumes this implementation.
Further reading
Section titled “Further reading”- Hugging Face
tokenizersByteLevel (tokenizers/src/pre_tokenizers/byte_level.rs,bytes_char): the same table in Rust, built once in alazy_static, plusadd_prefix_spaceand offset tracking. - OpenAI
tiktokenuses no character map at all: ranks are keyed by raw bytes and stored base64 encoded in.tiktokenfiles.tiktoken/load.py(data_gym_to_mergeable_bpe_ranks) rebuilds this map to read GPT-2’s original files. - openai/gpt-2,
src/encoder.py: the original 2019 function, with the comment explaining why whitespace and control characters are avoided. - Rosen, Discrete Mathematics and Its Applications, section 2.3, “Functions”.
- Radford et al., “Language Models are Unsupervised Multitask Learners” (2019), section 2.2.
Key terms
Section titled “Key terms”- Injective: no two inputs share an output; for a dict, no value appears twice.
- Surjective onto : every element of is the output of some input; the image equals .
- Bijective: both injective and surjective; exactly the functions that have an inverse.
- Image: the set of outputs that actually occur, .
- Pigeonhole principle: inputs cannot produce more than distinct outputs, so for equal sizes injective and surjective coincide.
- Byte map: GPT-2’s fixed bijection from the 256 byte values to 256 visible, non-whitespace characters.
Summary
Section titled “Summary”- A finite function is injective when no two inputs share an output, surjective onto a set when every element of that set is hit, and bijective when both; only a bijection has an inverse.
- Between two finite sets of the same size, injective, surjective, and bijective are the same thing, so 256 distinct outputs from 256 bytes is enough to prove the byte map is invertible.
- GPT-2 maps every byte to a visible, non-whitespace character so a vocabulary of byte strings can live in JSON and a merges file can split on spaces.
- The table is built from a rule (three kept ranges, then for the -th remapped byte), and it equals the one every GPT-2 style vocabulary uses, byte for byte, so byte-level BPE can load GPT-2 and SmolLM2 tokenizers.
Review questions
Section titled “Review questions”-
Why does
is_injectiveiterate overf.values()and never over the keys?Answer
Injective means no two inputs share an output, so the repeats to look for are among the outputs. The keys of a dict are distinct by construction, so checking them would always return
Trueand prove nothing. -
Why does
inverseraise on a repeated value instead of building{v: k for k, v in f.items()}?Answer
The comprehension silently keeps the last key for a repeated value, so it returns a “function” that is not the inverse of anything: one preimage is lost. In a tokenizer that means two ids share one string and decoding one of them returns the other. Raising, with both keys named, turns that into an immediate error.
-
In
bytes_to_unicode, why is the remapped characterchr(256 + n)and notchr(256 + b)?Answer
GPT-2 assigns the code points U+0100 to U+0143 consecutively, in byte order, to the 68 remapped bytes. counts those bytes, so it runs from 0 to 67.
chr(256 + b)would still be injective and visible, but for DEL (0x7F) it gives U+017F instead of U+0121ġ, so no real vocabulary would load. -
Why is it enough to show the map is injective to conclude it is a bijection onto its image, and why does
decode_charsstill need to check its input?Answer
Every function is surjective onto its own image, so injective plus “onto the image” is a bijection between the 256 bytes and the 256 image characters. But the image is not all of Unicode: a real space or
ńhas no preimage.decode_charsis defined only on the image, so it must reject anything else. -
encode_bytes("é")raisesTypeError. Why not encode the string’s code points?Answer
The map is defined on bytes.
"é"is one code point, U+00E9, but two UTF-8 bytes,C3 A9, and the vocabulary is keyed by the encoding of those two bytes,"é". Treating the code point as a byte gives"é", which is wrong, and for any character above U+00FF there is no single byte at all. The caller must choose the encoding (.encode("utf-8")).