Sub topic 1
Why Language Models Need Subword Units
Prerequisites
This chapter assumes that you can write basic Python with dictionaries, tuples, and loops. You should know that a language model reads a token, which is one unit of input such as a word or piece of a word, and that you can count item frequencies with collections.Counter.
Vocabularies and the out-of-vocabulary problem
A model maps each token to an integer ID using a fixed vocabulary. A word-level vocabulary fails on any word it has not seen, such as a rare name or a misspelling. That word becomes an out-of-vocabulary (OOV) token, and the model loses its meaning. A character-level vocabulary never produces OOV tokens, but sequences become long and the model must learn spelling from scratch.
Subword units sit between these extremes. Common words stay whole, and rare words split into known pieces. For example, "unhappiness" might become "un", "happi", and "ness". The vocabulary stays a manageable size, and every input can be represented.
Normalisation and pre-tokenisation before subword splitting
Tokenisers usually normalise text first, for example by applying Unicode normalisation and lowercasing. Pre-tokenisation then splits the text into words, typically on whitespace and punctuation. Subword merges run inside each word, so a merge never joins the end of one word to the start of the next.
Byte Pair Encoding: learning merges from a corpus
Byte Pair Encoding (BPE) is a method that builds a vocabulary by repeatedly merging the most frequent adjacent pair of symbols. Each word starts as a sequence of characters plus an end-of-word marker </w>. The trainer counts every adjacent pair, merges the most frequent one, and repeats. It records each merge in order, and the encoder applies those merges in the same order to new text.
The following code runs three merges on a small corpus:
from collections import Counter
def get_pair_counts(words):
pairs = Counter()
for symbols, freq in words.items():
for pair in zip(symbols, symbols[1:]):
pairs[pair] += freq
return pairs
def merge_pair(words, pair):
merged = Counter()
for symbols, freq in words.items():
out, i = [], 0
while i < len(symbols):
if i < len(symbols) - 1 and (symbols[i], symbols[i + 1]) == pair:
out.append(symbols[i] + symbols[i + 1])
i += 2
else:
out.append(symbols[i])
i += 1
merged[tuple(out)] += freq
return merged
corpus = ["low"] * 5 + ["lower"] * 2
words = Counter(tuple(w) + ("</w>",) for w in corpus)
merges = []
for _ in range(3):
pairs = get_pair_counts(words)
if not pairs:
break
best = max(pairs, key=pairs.get)
words = merge_pair(words, best)
merges.append(best)
print(merges)The output is [('l', 'o'), ('lo', 'w'), ('low', '</w>')]. The pairs ('l', 'o') and ('o', 'w') both occur 7 times, so max picks the first one it meets.
Exercise
In the corpus above, which pair is merged second, and how many times does it occur?
Show answer
The pair ('lo', 'w') is merged second. It occurs 7 times, because "low" appears 5 times and "lower" appears 2 times, and both contain "lo" followed by "w".