Encode a word with ranked BPE merges
Why it matters tiktoken and Hugging Face tokenizers encode every prompt with this loop.
Applying a trained BPE vocabulary means repeatedly merging the adjacent pair with the best (lowest) rank.
Write bpe_encode(word, ranks). Start with the list of characters. While any adjacent pair is in ranks (a dict from (a, b) to rank), find the pair with the lowest rank and merge every non-overlapping occurrence of it, scanning left to right. Return the final list of tokens.
def bpe_encode(word, ranks)Example
bpe_encode("aaab", {("a", "a"): 0, ("aa", "b"): 1}) merges to ["aa", "a", "b"] first, then no "aa"+"b" pair is adjacent, so the answer is ["aa", "a", "b"].
Understand the idea
A trained BPE tokenizer is a list of merges in the order they were learned, so each pair has a rank (lower means learned earlier). To encode a word, start from single characters and keep merging the adjacent pair with the lowest rank until no known pair is left. Worked example: word 'lower', ranks {('o', 'w'): 0, ('e', 'r'): 1, ('l', 'o'): 2, ('ow', 'er'): 3}. Start [l, o, w, e, r]. Known pairs are lo (2), ow (0), er (1); the lowest is ow, giving [l, ow, e, r]. Now pairs: l-ow unknown, ow-e unknown, er (1), so merge er: [l, ow, er]. Next ow-er (3) merges: [l, ower]. l-ower is unknown, so stop. Merging the leftmost known pair (lo) first would give a different and wrong result. Rule: loop: among adjacent pairs present in ranks, pick the lowest rank; scan left to right and merge every non-overlapping occurrence of that exact pair; repeat until no adjacent pair is in ranks. Used in: GPT-2, tiktoken and most LLM tokenizers at inference time.
Shapes and data flow
['l','o','w','e','r'] -> lo -> low -> er -> ['lower']