Greedy Longest-Match Subword Encoder Built on a Byte Trie
Data Structure DesignModel answerLast updated
Design and implement a deterministic subword encoder that uses a trie for longest-match lookup, with lossless Unicode handling, versioned vocabularies, tests, and a comparison with BPE and WordPiece.
You are building the text-preprocessing stage of a large language model training pipeline. The stage must convert raw text into integer token IDs and back, using a fixed, pre-trained vocabulary and a greedy longest-match strategy backed by a prefix trie.
Design and implement the component, covering the following:
- API. Define the interface. At a minimum it should include a way to build from a vocabulary, a way to turn text into IDs, and a way to turn IDs back into text. Say how special tokens are handled.
- Unicode. Explain how you deal with multi-byte UTF-8, emoji (including joined sequences), and CJK text.
- Normalization. Decide whether to apply Unicode normalization (NFC, NFKC, or none) and whether to change case. Justify the choice for pretraining data that includes code and math.
- Whitespace and punctuation. State the rules for how spaces and punctuation attach to tokens, and whether you pre-split text.
- Unknown input. Describe the fallback when no vocabulary entry matches.
- Complexity. Analyze time and memory for tokenizing and for storing the trie.
- Vocabulary updates. Explain how new tokens could be added over time without breaking models or data that already exist.
- Testing. Propose tests that target tricky inputs.
- Alternatives. Compare this approach with BPE and WordPiece, and discuss throughput and memory trade-offs in production.
Write working code for the core data structure and the tokenize and detokenize operations, and explain your reasoning as you would to a reviewer.
Hints
Hint 1
Think about what the trie is keyed on. If it is keyed on raw UTF-8 bytes rather than characters, multi-byte characters, emoji and CJK need no special cases, and you can guarantee that every possible input is representable.
Hint 2
Ask what 'lossless' should mean here. If all 256 single-byte values are always in the vocabulary, no input can ever be unknown, and decode(encode(x)) can equal the normalized input. Then decide which normalization preserves that property without corrupting code or math.
Hint 3
For updates, ask what is tied to token IDs (embedding rows, already-tokenized shards). That tells you IDs must be append-only and the vocabulary must be versioned, and that adding a token changes how old text would be segmented.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify requirements
- Workload: offline batch preprocessing at very large scale (trillions of tokens), so per-byte throughput dominates. Output must be deterministic.
- Vocabulary: fixed and trained elsewhere, roughly 32k to 256k entries, with a maximum token length L of about 16 to 32 bytes.
- Correctness bar:
detokenize(tokenize(x)) == normalize(x)for every input, since pretraining data contains code, math, emoji and many scripts, and lossy handling becomes training noise. - Rough scale: 10 TB at 50 MB/s per core is about 55 core-hours, which is minutes on ~1,000 cores. The inner loop cost is what matters.
2. API
build(vocab: list[str], specials: list[str] = []) -> None # id = list index
tokenize(text: str) -> list[int]
detokenize(ids: list[int]) -> str
add_tokens(tokens: list[str]) -> list[int] # append-only ids
Special tokens are matched by a separate step outside the trie, and only when the caller explicitly allows them. Otherwise user text containing the literal string of a special token would be able to forge control tokens.
3. Key design decisions
Work on bytes, not code points. Key trie edges by UTF-8 byte. A CJK character is three bytes and an emoji is four. A frequent character simply exists in the vocabulary as a multi-byte entry, and a rare one decomposes into bytes. No script-specific logic is needed, and joined emoji sequences work the same way.
Byte fallback instead of an unknown token. Insert all 256 single-byte tokens into the vocabulary. Any position where nothing longer matches is covered by a byte token, so nothing is ever unknown and the round trip is exact. An unknown token destroys information.
Normalization. Use NFC or none.
- NFKC folds ligatures, full-width forms and superscripts, which is lossy and can alter code and math.
- Lowercasing removes signal the model should learn.
- Whatever you pick must be applied identically at training and inference time and recorded in the vocabulary metadata.
Whitespace and punctuation. Allow a leading space to be part of a token (" the" is one entry). Optionally pre-split with a regex into runs of letters, digits, punctuation and whitespace so matches never cross categories. That makes segmentation more consistent and bounds match length.
4. Implementation
import unicodedata
class _Node:
__slots__ = ("children", "token_id")
def __init__(self):
self.children = {} # byte value -> _Node
self.token_id = None
class TrieTokenizer:
def __init__(self, normalization="NFC"):
self.normalization = normalization
self.root = _Node()
self.id_to_bytes = []
def _insert(self, b: bytes) -> int:
node = self.root
for byte in b:
node = node.children.setdefault(byte, _Node())
if node.token_id is None:
node.token_id = len(self.id_to_bytes)
self.id_to_bytes.append(b)
return node.token_id
def build(self, vocab):
for tok in vocab:
b = tok.encode("utf-8")
if not b:
raise ValueError("empty token")
self._insert(b)
for v in range(256): # guarantee byte fallback
self._insert(bytes([v]))
def add_tokens(self, tokens):
return [self._insert(t.encode("utf-8")) for t in tokens]
def _norm(self, text):
return unicodedata.normalize(self.normalization, text) if self.normalization else text
def tokenize(self, text):
data = self._norm(text).encode("utf-8")
ids, i, n = [], 0, len(data)
while i < n:
node, j = self.root, i
best_id, best_end = None, i
while j < n:
node = node.children.get(data[j])
if node is None:
break
j += 1
if node.token_id is not None:
best_id, best_end = node.token_id, j
ids.append(best_id) # never None thanks to byte fallback
i = best_end
return ids
def detokenize(self, ids):
raw = b"".join(self.id_to_bytes[i] for i in ids)
return raw.decode("utf-8", errors="replace")
A complete id sequence always decodes cleanly. A partial sequence (for example during streaming generation) may end mid-character, so a streaming decoder should hold back incomplete trailing bytes instead of emitting the replacement character.
5. Complexity
- Tokenize: O(n·L) worst case for n bytes, since each start position walks at most L levels. In practice close to O(n), because most walks stop after a few bytes and each walk advances by the matched length.
- Strictly linear time: add Aho-Corasick-style failure links (the idea behind linear-time WordPiece matching) so a long failed walk is not rescanned.
- Memory: proportional to the total bytes across all tokens. With Python dicts that is on the order of 100 bytes per node, so about 1M nodes costs around 100 MB. A double-array trie with two int32 arrays needs about 8 bytes per node, under 10 MB, which fits in cache and gives predictable transitions.
- Detokenize: O(output bytes).
6. Incremental vocabulary updates
- IDs are append-only. Embedding rows are bound to IDs, so never renumber. New tokens get new IDs, and the embedding and output matrices are extended, with new rows initialized from, say, the mean of the embeddings of the token's old pieces.
- Insert is O(|token|) in a mutable trie. For a compact double-array trie, rebuild offline and swap it in atomically.
- Delete by clearing the node's ID and retiring it permanently.
- Version the vocabulary together with the normalization config and stamp every tokenized shard. Adding a token changes how existing text segments, so data tokenized under different versions is not comparable.
7. Tests
- Property test (for example with Hypothesis) over arbitrary Unicode including astral characters, combining marks and right-to-left text:
detokenize(tokenize(s)) == normalize(s). - Empty string gives
[]. Very long whitespace runs must not blow up time or memory. - Joined emoji and skin-tone modifiers must round trip even when they fall back to byte tokens.
- Combining sequences such as
"e\u0301"versus"é": confirm both normalize to the same IDs under NFC. - Invalid or lone surrogates in input: decide whether to reject or replace, and test that choice.
- Greedy-specific cases: a vocabulary where a longer match blocks a better overall split (for example tokens
ab,bcd,a,b,c,donabcd) to document that greedy is not optimal. - Special-token injection: user text containing a special token's literal must not produce the special ID.
- Determinism: identical output across runs, platforms and shards.
8. Comparison with BPE and WordPiece
| Aspect | Trie + greedy longest match | BPE (merge rules) | WordPiece |
|---|---|---|---|
| Segmentation | Longest prefix at each step | Apply learned merges in priority order | Greedy longest match within a word, with continuation markers |
| Training | Not included, vocabulary given | Learns merges from corpus | Learns vocabulary by likelihood |
| Inference cost | Near linear, simple loop | Naive is quadratic per word, fast versions use priority queues or caches | Linear with failure links |
| Memory | Small with a double-array trie | Merge table plus caches | Similar to trie |
| Fidelity to training | May differ from how the vocabulary was trained | Matches training exactly | Matches by design |
Key trade-off: greedy longest match is fast and simple, but if the vocabulary was trained with BPE, greedy matching can produce different segmentations than the merge procedure. That mismatch hurts the model, so use the trie only when the training algorithm was itself longest-match, or verify equivalence on a large sample.
9. Common mistakes
- Using
<unk>instead of byte fallback and losing data. - Applying NFKC to code and math corpora.
- Renumbering IDs after a vocabulary change.
- Letting user text produce special tokens.
- Decoding partial streams naively and emitting replacement characters.
- Allowing the trie to match across word categories, which makes tokens inconsistent.