Concepts / Byte Pair Encoding (BPE) Tokenizer

Byte Pair Encoding (BPE) Tokenizer

Tokenization breaks raw text into tokens, which can be words or characters, and then converts those tokens into integer token IDs.

  • Programming
Interactive lab

Try it: Text Vectorization: Tokens to Vectors

The text-to-tensor pipeline: standardize, split into tokens, build a frequency-ranked vocabulary with padding and [UNK], map tokens to integer ids, pad or truncate, then one-hot or multi-hot encode and look the ids up in an embedding table.

How it works

  1. Standardize: lowercase and delete punctuation.
  2. Split on whitespace into tokens.
  3. Build the vocabulary: 0 = padding, 1 = [UNK], then words by frequency (ties: first appearance), capped at max tokens.
  4. Map each token to its id (1 if it did not make the vocabulary), then pad with 0 or truncate to the sequence length.
  5. Encode: one-hot rows per position or one multi-hot row per text; embed: id k selects row k of the embedding table.

Default run (18 steps): Raw text (59 characters): "The movie was great. The plot was great, the acting wasn't!". A model cannot read strings, so it is turned into numbers step by step. … Embedding lookup: id k selects row k of a fixed 8 x 3 table, giving a (8, 3) dense matrix instead of (8, 8) sparse one-hots. Row 0 (padding) is looked up too; a trained Embedding layer would learn these rows.

Simplified: Bounded ASCII text (up to 200 characters, 40 tokens), whitespace splitting only, and a small FIXED embedding table (a real Embedding layer learns its rows). The multi-hot vector keeps the padding slot (always 0) so its positions line up with the ids.

Educational simulation

Loading the simulation…

Why a Model Cannot Read Text Directly

A large language model cannot read a sentence the way you do. Before any learning can happen, text has to be turned into a form that a deep learning model can process. That preparation happens in two stages. The first stage converts raw text into discrete integer identifiers. The second stage converts those identifiers into continuous vectors that a model can work with. As you read, keep one question in mind: what does the text look like after each step?

What do you think happens?

If a model is going to process the sentence 'the cat sat', what form must that text take before any learning can happen?

Reveal answer
Answer:

The text must be converted into a discrete set of integer identifiers, and then those identifiers must be converted into continuous vectors.

Raw characters are not something a deep learning model can compute with directly. Tokenization splits the text into units, each unit becomes an integer token ID, and an embedding layer turns those IDs into vectors.

Tracing the Pipeline from String to Integers

The first step is tokenization. Raw text is broken into tokens, and a token can be a word or a character. Tokenization is the general process of breaking text into these units. After that, each token is converted into an integer representation called a token ID. So the pipeline runs from a string of characters, to a list of tokens, to a list of integers.

Raw stringcharactersTokenswords or charactersToken IDsintegersEmbedding vectorscontinuous valuestokenizationconverted to IDembedding lookup
What happens to a raw string, in order: where is it split into tokens, where do the tokens become integer IDs, and where do the IDs become vectors?

Notice that the output of tokenization is discrete. Each token ID is a whole number that names one token. The text is no longer a continuous stream of characters but a sequence of labels drawn from a fixed set. That discreteness is what makes the next stage necessary, because whole numbers on their own are not a rich representation for a deep learning model.

Token IDs Versus Embedding Vectors

Token IDs are integers, and integers alone are not a rich representation for a deep learning model. An embedding layer in PyTorch solves this by functioning as a lookup operation. It takes a token ID and retrieves the vector that corresponds to it. The retrieved embedding vectors provide continuous representations of tokens, and the source describes this as crucial for training deep learning models such as LLMs.

Token ID 2a single integerRow 0vector for ID 0Row 1vector for ID 1Row 2vector for ID 2Row 3vector for ID 3lookup selects
How does an integer token ID select one specific row of the embedding matrix, and how is that row different from the ID itself?
Key point

The token ID is a label that points at a position. The embedding vector is the content stored at that position. The ID is discrete and whole-numbered; the vector is a continuous list of values that the model can compute with.

The contrast between the two stages is the key idea. Token IDs are discrete whole numbers, one per token. Embedding vectors are continuous representations retrieved by those IDs. The lookup is what moves a token from a label into a form suited to deep learning.

What BPE Is and Where It Comes From

Definition

Byte Pair Encoding, usually abbreviated BPE, is a tokenization method used in natural language processing. It is the method behind the tokenizer used for GPT-2, and the source also names it as the approach used for LLMs such as GPT-2 and GPT-3.

Tokenization is the general process of breaking text into tokens. BPE is one specific tokenizer that performs that process, and its distinguishing feature is how it treats words that lie outside its vocabulary. A tokenizer built only on whole words runs into trouble when it meets a word it has never seen. BPE handles such words efficiently by breaking the unfamiliar word into subword units or, if necessary, into individual characters, so the word does not have to be discarded.

The name points to the core operation. A BPE tokenizer works on pairs of adjacent symbols and combines frequent pairs into single units. Repeating that combination step gradually builds a vocabulary of units that can be longer than one character and shorter than a whole word. Because those units are pieces of words, BPE belongs to the family of subword tokenization methods.

The approach was introduced to machine translation in the research paper titled Neural Machine Translation of Rare Words with Subword Units, published in 2015 by Sennrich et al. and available on arXiv. Its title states the motivation directly: rare words are the hard case, and subword units are the proposed way to handle them.

Why Subword Units Sit Between Words and Characters

There are two obvious extremes. If a tokenizer treats every whole word as one token, it needs a huge vocabulary, and any word it has not seen during training has no entry at all. If it treats every character as one token, the vocabulary stays small, but the sequences become long and the individual units carry little meaning on their own. Subword units sit between these extremes. Common words can stay whole, while rare or unfamiliar words are assembled from smaller pieces that the vocabulary already contains.

This is also why subword units let a tokenizer represent rare words. A rare word does not need its own dedicated entry, because it can be spelled out as a combination of smaller pieces that the vocabulary already holds.

Tracing One Merge Step

BPE builds subword units by repeatedly merging the most frequent adjacent pair of symbols into a new unit. Each merge adds one entry to the vocabulary. Here is a deliberately small example so you can watch the rule work. Imagine the training text has been split into single symbols, and the sequence is: t h e _ t h e _ t h i s. The underscore marks a space. Scan the sequence for adjacent pairs. The pair t h appears three times, the pair h e appears twice, and the other pairs appear at most once. The most frequent pair is t h.

Before

t h e _ t h e _ t h i s

12 symbols, with the pair t h occurring 3 times

After

th e _ th e _ th i s

9 symbols, with th as a single new unit

tthhee__thteh_eth_itshis
What does the symbol sequence look like before and after the most frequent adjacent pair t h is merged into one new symbol, and how many tokens does that remove?

What do you think happens?

Before you read on: after every occurrence of t h is merged into th, how many symbols does the sequence contain?

Reveal answer
Answer:

9 symbols, down from 12.

The pair t h occurs three times. Each occurrence turns two symbols into one, so the sequence shrinks by one symbol per occurrence: 12 minus 3 equals 9.

Worked example

Tracing one merge on the sequence t h e _ t h e _ t h i s

Starting from single symbols, apply one BPE merge: find the most frequent adjacent pair, merge it into a new unit, and report the effect on the token sequence.

  1. 1
    Split into symbols

    The starting sequence is t h e _ t h e _ t h i s, with 12 separate symbols.

  2. 2
    Count adjacent pairs

    The pair t h appears three times, the pair h e appears twice, and every other pair appears at most once.

  3. 3
    Pick the most frequent pair

    t h is the most frequent adjacent pair, so it is the one that gets merged.

  4. 4
    Merge and record

    Each occurrence of t h becomes the single unit th. The unit th is added to the vocabulary.

  5. 5
    Check the effect

    The sequence becomes th e _ th e _ th i s, which has 9 symbols. The merge removed one token for each of the three occurrences.

Result

One merge reduced the sequence from 12 symbols to 9 and produced one new vocabulary unit, th.

Notice what the merge did and did not do. It did not look at whole words; it looked only at which adjacent symbols sat next to each other most often. The new unit th is now available as a building block, so later merges can combine it with other units.

Growing the Vocabulary by Repeated Merges

The loop between counting and merging is the heart of the method. Each pass looks at the current sequence of units, finds the pair that occurs most often, and replaces that pair with a single unit. Because each merged unit becomes a building block for later merges, longer units can emerge from shorter ones over many passes. In the tiny example above, th could later join with e or with another unit, depending on what the counts show at that point.

Count adjacent pairsMerge most frequentpairAdd new unitVocabulary grows byonenextrecordentry addedrepeat on new sequence
How does the vocabulary grow over repeated rounds of counting adjacent pairs and merging the most frequent one?

The example is deliberately small. Real training runs over a large body of text and performs many merges, but the rule at each step is the same: find the most frequent adjacent pair, merge it, and record the new unit. The material used for this article describes the repeated loop but does not specify a fixed stopping rule, so treat the number of merges as a design decision of the training run rather than something this article fixes.

Handling Words the Vocabulary Has Never Seen

Suppose the tokenizer meets a word that is not in its learned vocabulary. BPE does not give up on it. The unfamiliar word is broken down into subword units that the vocabulary does contain. If the word cannot be covered by larger pieces, the tokenizer falls back to individual characters. In either case the pieces are still represented, so the word is encoded rather than discarded.

This is why the choice of tokenizer affects how a model handles spellings it has never seen before. A model that receives an unfamiliar word still receives a sequence of tokens it can work with, even if those tokens are smaller than the word itself.

Common Mistakes When Reading About BPE

  • Common mistake

    Treating a token ID as if it were the embedding vector

    What it looks like

    Assuming that token ID 2 is itself a list of continuous numbers that the model learns from

    Why it fails

    A token ID is a single whole number that names a token. The embedding layer uses that number as a lookup key and retrieves a separate vector.

    Do this instead

    Keep the two apart: the ID is the discrete label, and the embedding vector is the continuous representation retrieved by that label.

  • Common mistake

    Assuming an unknown word is dropped from the input

    What it looks like

    Believing that a word missing from the vocabulary simply disappears from the token sequence

    Why it fails

    BPE handles unknown words by breaking them into subword units or individual characters, so their pieces are still represented.

    Do this instead

    Think of an unknown word as being spelled out in smaller pieces that the vocabulary already contains.

  • Common mistake

    Thinking BPE merges whole words that occur often

    What it looks like

    Expecting the rule to merge the word the into one unit because it is common

    Why it fails

    BPE works on pairs of adjacent symbols, not on whole words. In the worked example, the merge was driven by how often t h occurred next to each other.

    Do this instead

    Count adjacent symbol pairs, pick the most frequent one, and merge only that pair.

  • Common mistake

    Confusing training with application

    What it looks like

    Believing every new sentence triggers a fresh round of merges

    Why it fails

    Training builds the vocabulary by repeatedly merging pairs. Application then uses that vocabulary to split new text.

    Do this instead

    Separate the two stages in your head: merges belong to training, and splitting belongs to application.

Where to Inspect or Build BPE Yourself

The material for this article points to three concrete resources. Each one lets you move from the concept to real code or to a visual demonstration, and each suits a different goal. Use an implementation when you want to see how the merge loop is written, and use an interactive demonstration when you want to watch merges happen on a text you choose. The original paper by Sennrich et al. is the primary reference for the approach and its motivation for rare words.

  1. 1
    Sennrich, R., Haddow, B., and Birch, A. (2015). Neural Machine Translation of Rare Words with Subword Units. Available on arXiv.

Practice: Tracing a Merge by Hand

EASY

Start from the symbol sequence a b a b c. Find the most frequent adjacent pair, merge it into one new unit, and write the resulting sequence. How many symbols did the merge remove?

Hints
  • List every adjacent pair first: a b, b a, a b, b c.
  • Count how often each pair appears. The pair a b appears twice; b a and b c appear once.
  • After merging a b into ab, the sequence should be ab ab c. Count the symbols before and after.
MEDIUM

Explain, in your own words, why the ID 4 and the embedding vector retrieved for ID 4 are different kinds of things, and which one a deep learning model computes with directly.

Hints
  • Ask whether the ID is a continuous list of values or a single discrete whole number.
  • Recall which stage produces discrete identifiers and which stage produces continuous representations.

Key Takeaways

  • Tokenization breaks raw text into tokens, which can be words or characters, and then converts each token into an integer token ID.
  • An embedding layer in PyTorch acts as a lookup: it takes a token ID and retrieves a continuous vector for that token. The ID is a discrete label; the vector is the representation a model computes with.
  • BPE builds subword units by repeatedly merging the most frequent adjacent pair of symbols. In the worked example, one merge turned t h e _ t h e _ t h i s into th e _ th e _ th i s, removing one token per occurrence.
  • Unknown words are not discarded: BPE breaks them into subword units or, if necessary, individual characters. BPE is the method behind the tokenizer used for GPT-2 and GPT-3, and it was introduced to machine translation by Sennrich et al. in 2015.

Related concepts

More concepts starting with B