Predict whether tokenizer.encode('world') and tokenizer.encode(' world') produce the same token IDs in tiktoken.
Same topic, related formats. Practice these next.
Same topic, related formats. Practice these next.
Using tiktoken with cl100k_base:
```python
import tiktoken
enc = tiktoken.get_encoding('cl100k_base')
print(enc.encode('world'))
print(enc.encode(' world'))
```
Predict whether the two calls produce the same list of token IDs. If different, explain why.Different IDs: byte-level BPE folds the leading space into the token, so ' world' and 'world' are distinct entries with distinct IDs.
Imagine your phone's autocomplete keeps two separate buttons: one for the word right after a space, like the ' apple' you tap mid-sentence, and one for 'apple' stuck to the start of a line. They look almost the same to you, but the keyboard files them in different slots. A byte-level tokenizer does the same thing. The space in front of a word is glued onto the word and becomes part of which button gets pressed, so the version with a space and the version without get different ID numbers.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example. Click to expand.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example.
Everything important, quickly.
2 min: different IDs + space folded into the token + frequency reason + lossless decode + the concatenation bug + the apply_chat_template guard.
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
print(enc.encode("world")) # e.g. [14957] -> no leading space
print(enc.encode(" world")) # e.g. [1917] -> leading space folded in
# Same letters, different IDs. Decode round-trips the space:
print(repr(enc.decode([1917]))) # ' world'
# The trap: gluing pieces without spaces shifts the boundary token.
print(enc.encode("hello" + "world")) # 'world' has no leading space
print(enc.encode("hello" + " world")) # natural spacingReal products, models, and research that use this idea.
What an interviewer would ask next. Try answering before peeking at the approach.
Red flags and common mistakes that signal junior thinking. Click to expand.
Assuming the tokenizer trims whitespace, so the same word always gets the same ID regardless of a leading space.
The night-before-the-interview bullets. Scan these on the way to the call.
Primary sources. Skim if you want the original framing.