04 · Inspect a real tokenizer¶
About 15–20 minutes · independent of other units
A BPE vocabulary is learned from data, so its tokens are chunks that were frequent in that data, and some of them look like meaningful words. Here we inspect the outputs of the already-installed tiktoken library as a measuring instrument. We use its API, not its implementation.
You will be able to: distinguish bytes from token IDs on real inputs; measure bytes per token; check exact reconstruction; observe how whitespace and text changes affect segmentation.
The fixed encoding is GPT-2, so the vocabulary does not change when you edit the examples. Loading its encoding may download a cached vocabulary file on the first run. There is no model inference or API key involved.
import tiktoken
encoding = tiktoken.get_encoding("gpt2")
print("Encoding:", encoding.name)
print("Vocabulary size:", encoding.n_vocab)
Encoding: gpt2 Vocabulary size: 50257
1 · Inspect token IDs and the bytes they identify¶
Predict: does the leading space belong to a token? Does one token always decode cleanly on its own?
The display uses UTF-8 replacement characters only for readability. Those replacement characters are not changes to the token's actual bytes.
Python: encode_ordinary() returns IDs; decode_single_token_bytes() retrieves one token’s byte payload.
text = "hello world! 猫🙂"
ids = encoding.encode_ordinary(text)
print("Text:", repr(text))
print("IDs:", ids)
print(f'{"ID":>8} {"bytes":30} display only')
for token_id in ids:
payload = encoding.decode_single_token_bytes(token_id)
print(f'{token_id:>8} {str(payload):30} {payload.decode("utf-8", errors="replace")!r}')
payload = b"".join(encoding.decode_single_token_bytes(i) for i in ids)
assert payload == text.encode("utf-8")
assert encoding.decode(ids) == text
print("Exact reconstruction: PASS")
Text: 'hello world! 猫🙂'
IDs: [31373, 995, 0, 13328, 234, 104, 8582, 25081]
ID bytes display only
31373 b'hello' 'hello'
995 b' world' ' world'
0 b'!' '!'
13328 b' \xe7' ' �'
234 b'\x8c' '�'
104 b'\xab' '�'
8582 b'\xf0\x9f' '�'
25081 b'\x99\x82' '��'
Exact reconstruction: PASS
2 · Compare byte length and token length¶
Bytes per token is an observable compression measure here, not a score of how meaningful the words are. These examples are not matched translations, so they cannot establish a language ranking.
Predict: will repeating a letter, changing case, or adding spaces preserve the token count?
Python: Empty lists are falsey. x if condition else y selects a value; :.2f displays two decimal places.
samples = [
"hello", " hello", "Hello", "HELLO",
"tokenization", "tokenization tokenization",
"猫喜欢阳光。", "🙂🙂🙂", "aaaaaaaaaaaa", " ", "",
]
print(f'{"text":32} {"bytes":>6} {"tokens":>7} {"bytes/token":>12}')
for sample in samples:
token_ids = encoding.encode_ordinary(sample)
byte_count = len(sample.encode("utf-8"))
ratio = f"{byte_count / len(token_ids):.2f}" if token_ids else "n/a"
print(f'{sample!r:32} {byte_count:>6} {len(token_ids):>7} {ratio:>12}')
assert encoding.decode(token_ids) == sample
text bytes tokens bytes/token 'hello' 5 1 5.00 ' hello' 6 1 6.00 'Hello' 5 1 5.00 'HELLO' 5 3 1.67 'tokenization' 12 2 6.00 'tokenization tokenization' 25 4 6.25 '猫喜欢阳光。' 18 14 1.29 '🙂🙂🙂' 12 6 2.00 'aaaaaaaaaaaa' 12 3 4.00 ' ' 3 3 1.00 '' 0 0 n/a
3 · Encoding parts separately can change segmentation¶
A tokenizer can be lossless while encode(left) + encode(right) differs from encode(left + right). A boundary can prevent merges that would otherwise be available.
Predict: what happens if a stream splits hello into hel and lo?
Python: + concatenates strings and lists; it does not add the IDs elementwise.
left, right = "hel", "lo"
separate = encoding.encode_ordinary(left) + encoding.encode_ordinary(right)
together = encoding.encode_ordinary(left + right)
print("Separate:", separate)
print("Together:", together)
print("Same token IDs:", separate == together)
assert encoding.decode(separate) == left + right
assert encoding.decode(together) == left + right
Separate: [2978, 5439] Together: [31373] Same token IDs: False
4 · Special-token policy is explicit¶
The string <|endoftext|> can mean literal text or a reserved marker, depending on the encoding policy. Here we deliberately compare both interpretations. We are only observing GPT-2's convention, not prescribing the assignment's implementation.
Python: {marker} is a set literal, passed through the keyword argument allowed_special.
marker = "<|endoftext|>"
literal_ids = encoding.encode_ordinary(marker)
marker_ids = encoding.encode(marker, allowed_special={marker})
print("As literal text:", literal_ids)
print("As allowed special marker:", marker_ids)
assert encoding.decode(literal_ids) == marker
assert encoding.decode(marker_ids) == marker
As literal text: [27, 91, 437, 1659, 5239, 91, 29] As allowed special marker: [50256]
Your experiment · use a line of your own¶
Paste a short line into my_text. Predict the tricky boundaries, then inspect every token's bytes. Change only one thing and compare again: case, a space, punctuation, or a multilingual character.
my_text = "BPE constructs a vocabulary tailored to data."
my_ids = encoding.encode_ordinary(my_text)
print("IDs:", my_ids)
print("Token bytes:", [encoding.decode_single_token_bytes(i) for i in my_ids])
print("Characters:", len(my_text), "Bytes:", len(my_text.encode("utf-8")), "Tokens:", len(my_ids))
assert encoding.decode(my_ids) == my_text
IDs: [33, 11401, 34175, 257, 25818, 27571, 284, 1366, 13] Token bytes: [b'B', b'PE', b' constructs', b' a', b' vocabulary', b' tailored', b' to', b' data', b'.'] Characters: 45 Bytes: 45 Tokens: 9
What you found¶
- My text and prediction:
- A surprising boundary I observed:
- What my bytes-per-token measurement does and does not tell me:
- A round-trip property I would want my own tokenizer to satisfy:
- Why a single token's byte payload need not be valid UTF-8:
Toward the CS336 tokenizer: inspect bytes instead of guessing from printed text; measure actual sequence lengths; distinguish round-trip correctness from a particular segmentation. With these four notebooks done, the assignment's tokenizer section reads against concrete examples.
Reference: tiktoken public API and overview.