KatInterview

Greedy Longest-Match Subword Encoder Built on a Byte Trie

Data Structure DesignModel answer
HardModel answerData Structure Designtrietokenizerunicode

Last 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:

  1. 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.
  2. Unicode. Explain how you deal with multi-byte UTF-8, emoji (including joined sequences), and CJK text.
  3. 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.
  4. Whitespace and punctuation. State the rules for how spaces and punctuation attach to tokens, and whether you pre-split text.
  5. Unknown input. Describe the fallback when no vocabulary entry matches.
  6. Complexity. Analyze time and memory for tokenizing and for storing the trie.
  7. Vocabulary updates. Explain how new tokens could be added over time without breaking models or data that already exist.
  8. Testing. Propose tests that target tricky inputs.
  9. 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.