Tokenizers: BPE and Longest Match
✂️ What is a tokenizer? A tokenizer turns text into the integer ids a language model reads. Given a vocabulary of strings, greedy longest match scans left to right and at each position takes the longest vocabulary entry that fits, falling back to an unknown token. Byte-pair encoding (BPE) is how such vocabularies are built: start from single characters and repeatedly merge the most frequent adjacent pair.
Anthropic has asked the longest-match tokenizer in phone screens: in one report, longest match with an unknown token, then optimizing the loop to the longest vocabulary entry, then collapsing consecutive unknowns; in another, a plain loop was enough before the interviewer moved on (the question).
The Prompt
This is a string problem with an ML flavor, so the interviewer grades a correct loop first, then the complexity argument and the follow-up changes, done cleanly under time pressure.
"You're given a vocabulary that maps strings to token ids, and an id for unknown. Tokenize a string by greedy longest match: at each position, emit the id of the longest vocabulary entry starting there, or the unknown id for one character if nothing matches."
Clarifying Questions
You: What does the vocabulary look like, and can entries overlap, like "a", "ab" and "abc"?
Interviewer: A dict from string to int. Overlaps are the point. The unknown id is not used by any entry.
You: When nothing matches, I skip exactly one character and emit one unknown id?
Interviewer: Yes. Later I'll ask you to merge runs of unknowns.
You: How big are the inputs? That decides whether trying every end position is fine.
Interviewer: Text up to 10^5 characters, entries up to 20 characters, a few thousand entries.
You: Is the result a list of ids, and is the empty string allowed?
Interviewer: A list of ints; empty text gives an empty list.
What You'll Build
tokenize_naive(text, vocab, unk) -> list[int]: the reference, trying every end position.tokenize(text, vocab, unk, collapse_unk=False) -> list[int]: bounded by the longest entry.Trie(vocab).tokenize(text, unk, collapse_unk=False) -> list[int]: one walk per token.train_bpe(words, n_merges) -> list[pair]andbpe_encode(word, merges) -> tuple[str, ...].