Computer scienceData scienceNLPText processingText normalization

Tokenization

10 minutes read

Tokenization splits a sequence of characters into units called tokens. Tokens are usually words, numbers, or punctuation marks, but they can also be sentences or morphemes (parts of words). Tokenization is the first step of text preprocessing: before an NLP system can work out what a text means, it has to know which units the text consists of.

Tokenization issues

The main difficulty is deciding what counts as a token. Here is a simple example:

Tokenization sample

In this case, splitting the sentence at spaces is enough. English also has less obvious cases, though: what should a tokenizer do with apostrophes, or with a mix of numbers and letters?

Tokenization sample

Which option is best? The first one looks natural. The second one also makes sense, because "we're" is a contraction of "we are". The other options are possible too.

And should the name of a city like New York be one token, New York, or two, ["New", "York"]?

When you design a tokenizer, you have to decide how to handle:

  • Capitalization

  • The language of the text, including programming languages such as Python, where whitespace and indentation matter

  • Numbers and digits

  • Special tokens, which stand for something other than the text itself. They can mark the beginning or end of a text, serve a specific task (such as classification), or mask parts of the text during training. You'll see examples below.

The tokenizer granularity

Tokenizers differ in granularity: they split text into words, subwords, characters, or bytes.

Word tokenization was once popular but is rarely used now, for two main reasons. First, a word tokenizer can't handle words that weren't in its training data. Second, its vocabulary fills up with words that are very similar in meaning, such as classify, classification, classifiable, and classifier. Subword tokenization solves both problems: it keeps a root token ('class') and suffix tokens ('ify', 'ification', and so on), which keeps the vocabulary small.

The vocabulary size affects how much computation a model needs, because each token in the vocabulary has its own embedding vector. With subword units, a smaller vocabulary can still represent the language well.

A subword tokenization vocabulary contains both whole words and word fragments. A word that isn't in the vocabulary is split into known pieces. For example, if "uncharacteristically" isn't in the vocabulary, it can be represented as "un" + "character" + "istic" + "ally".

Character tokenization can handle any new word, since every word is made of letters, but it makes the model's job harder: the model has to learn to compose "p-l-a-y" instead of seeing "play" as one unit. Subword tokens also use the context window better. Each subword token usually covers several characters, so with a limit of 1,024 tokens, a subword tokenizer typically fits about three times more text than a character tokenizer.

Some models use byte-level tokenization and process text as raw UTF-8 bytes, without a vocabulary of words or subwords. Some subword tokenizers also fall back to byte tokens for characters they don't know, but they aren't byte-level tokenizers, since they use bytes only for these characters and not for the whole text.

WordPiece

WordPiece (introduced in 2012) is a subword tokenizer. It finds frequent character sequences in a training corpus and builds a vocabulary of subwords that can represent the text while keeping the vocabulary size manageable.

WordPiece starts with a vocabulary of single characters and then repeatedly merges two adjacent tokens into a new one. It picks the pair that most increases the likelihood of the training data, which favors pairs whose parts appear together much more often than apart. To encode a word, WordPiece splits it into the longest subwords it can find in the vocabulary and marks the pieces that don't start a word with ##.

Here is the uncased version of the BERT tokenizer on a regular English sentence and on Python code:

WordPiece tokenization example

WordPiece tokenization example based on the code input

The word 'uncharacteristically' is split into 6 tokens, 5 of which are marked as subword pieces. [CLS] is a special token at the start of every input, and its embedding is used for classification tasks. [SEP] separates sentences.

BERT's WordPiece tokenizer has 3 more special tokens:

  • [PAD] fills shorter sequences so that all sequences in a batch have the same length, as neural network training requires

  • [UNK] stands for a word that isn't in the model's vocabulary

  • [MASK] is used for masked language modeling. During training, random tokens in a sentence are replaced with [MASK], and the model learns to predict which word belongs there.

Byte pair encoding (BPE)

Byte pair encoding builds its vocabulary like WordPiece, by merging adjacent tokens, but it simply merges the most frequent pair each time. GPT models use byte-level BPE, which starts from bytes instead of characters. Any text can be split into bytes, so such a tokenizer never needs an unknown token, which makes it more flexible with unknown words than WordPiece.

Here is how the GPT-2 BPE-based tokenizer works:

An example of sentence tokenization with BPE

An example of code tokenization with BPE

This tokenizer keeps new lines, spaces, and tabs as tokens, which matters when LLMs work with code. It has one special token, <|endoftext|>. Newer OpenAI tokenizers, such as cl100k_base (GPT-4) and o200k_base (GPT-4o and later models), work like the GPT-2 tokenizer, but have much larger vocabularies, handle code better, and tend to use fewer tokens for the same text.

Conclusion

  • Tokenization splits text into tokens. Even in English, it involves decisions about apostrophes, capitalization, numbers, and special tokens.

  • Tokenizers work with words, subwords, characters, or bytes. Word tokenization is rarely used now, and subword tokenization is the usual choice.

  • BERT uses WordPiece, which chooses merges by likelihood and marks the pieces inside a word with ##.

  • GPT models use byte-level BPE, which merges the most frequent pairs, never needs an unknown token, and keeps whitespace, so it handles code well.

15 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo