Frame · dsa / ai-algorithms / 02-byte-pair-encoding-tokenizer.jsJavaScript
Byte-Pair Encoding Tokenizer: Training and Encoding
Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.
Same file as in the repo · ~20s timeout
From file header (JSDoc)
Byte-Pair Encoding Tokenizer: Training and Encoding
Problem: Implement a minimal character-level BPE tokenizer.
- `trainBPE(corpus, numMerges)` splits the corpus on whitespace into words,
represents each word as a list of characters, and repeatedly merges the
most frequent adjacent pair (counted across all words, weighted by word
frequency). Ties are broken by the lexicographically smallest pair
`a + " " + b`. Stop early when no pair occurs at least twice. Return the
ordered list of merges `[a, b]`.
- `encodeBPE(word, merges)` starts from characters and applies merges in
training order (earlier merges have higher priority), returning tokens.
Constraints:
- corpus length <= 10^5 characters, numMerges <= 1000
Example:
trainBPE("low low low lower lowest", 2) -> [["l","o"], ["lo","w"]]
encodeBPE("lowly", merges) -> ["low", "l", "y"]
Approach: Keep a map from word to its frequency and current symbol list.
Each round, count all adjacent pairs, pick the best, and rewrite every word
by replacing occurrences of that pair with the joined symbol. Encoding
repeatedly finds the adjacent pair with the lowest merge rank and joins it.
Training time O(numMerges * total symbols), encoding O(m * L) for a word of
length L, space O(total symbols + merges).
@param {string} corpus
@param {number} numMerges
@returns {[string, string][]}