下列文本提取自本地原版 PDF。图表和公式的准确布局请对照 PDF。
2.4 BPE Tokenizer Training
The BPE tokenizer training procedure consists of three main steps.
Vocabulary initialization
The tokenizer vocabulary is a one-to-one mapping from bytestring token to integer ID. Since we’re
training a byte-level BPE tokenizer, our initial vocabulary is simply the set of all bytes. Since there are
256 possible byte values, our initial vocabulary is of size 256.
Pre-tokenization
Once you have a vocabulary, you could, in principle, count how often bytes occur next to each other in
your text and begin merging them starting with the most frequent pair of bytes. However, this is quite
computationally expensive, since we’d have to take a full pass over the corpus each time we merge. In
addition, directly merging bytes across the corpus may result in tokens that differ only in punctuation
(e.g., dog! vs. dog.). These tokens would get completely different token IDs, even though they are likely
to have high semantic similarity (since they differ only in punctuation).
To avoid this, we pre-tokenize the corpus. You can think of this as a coarse-grained tokenization over the
corpus that helps us count how often pairs of characters appear. For example, the word 'text' might be a
pre-token that appears 10 times. In this case, when we count how often the characters ‘t’ and ‘e’ appear
next to each other, we will see that the word ‘text’ has ‘t’ and ‘e’ adjacent and we can increment their
count by 10 instead of looking through the corpus. Since we’re training a byte-level BPE model, each pre-
token is represented as a sequence of UTF-8 bytes.
The original BPE implementation of R. Sennrich et al. [3] pre-tokenizes by simply splitting on whitespace
(i.e., s.split(" ")). This method is still found in tokenizers based on SentencePiece (for instance the
Llama 1 and 2 tokenizer).
Most modern tokenizers use a regex-based pre-tokenizer, a practice from GPT-2; A. Radford et al. [6].
We’ll use a slightly prettier form of the original regex, fetched from
github.com/openai/tiktoken/pull/234/files:
>>> PAT = r"""'(?:[sdmt]|ll|ve|re)| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"""
It may be useful to interactively split some text with this pre-tokenizer to get a better sense of its
behavior:
>>> # requires `regex` package
>>> import regex as re
>>> re.findall(PAT, "some text that i'll pre-tokenize")
['some', ' text', ' that', ' i', "'ll", ' pre', '-', 'tokenize']
When using it in your code, however, you should use re.finditer to avoid storing the pre-tokenized
words as you construct your mapping from pre-tokens to their counts.
Compute BPE merges
Now that we’ve converted our input text into pre-tokens and represented each pre-token as a sequence of
UTF-8 bytes, we can compute the BPE merges (i.e., train the BPE tokenizer). At a high level, the BPE
algorithm iteratively counts every pair of bytes and identifies the pair with the highest frequency (“A”,
“B”). Every occurrence of this most frequent pair (“A”, “B”) is then merged, i.e., replaced with a new
token “AB”. This new merged token is added to our vocabulary; as a result, the final vocabulary after
BPE training is the size of the initial vocabulary (256 in our case), plus the number of BPE merge
operations performed during training. For efficiency during BPE training, we do not consider pairs that
cross pre-token boundaries.2 When computing merges, deterministically break ties in pair frequency by
preferring the lexicographically greater pair. For example, if the pairs (“A”, “B”), (“A”, “C”), (“B”, “ZZ”),
and (“BA”, “A”) all have the highest frequency, we’d merge (“BA”, “A”):
>>> max([("A", "B"), ("A", "C"), ("B", "ZZ"), ("BA", "A")])
('BA', 'A')
Special tokens
Often, some strings (e.g., <|endoftext|>) are used to encode metadata (e.g., boundaries between
documents). When encoding text, it’s often desirable to treat some strings as “special tokens” that should
2
Note that the original BPE formulation R. Sennrich et al. [3] specifies the inclusion of an end-of-word token. We do not
add an end-of-word-token when training byte-level BPE models because all bytes (including whitespace and punctuation)
are included in the model’s vocabulary. Since we’re explicitly representing spaces and punctuation, the learned BPE merges
will naturally reflect these word boundaries.
never be split into multiple tokens (i.e., will always be preserved as a single token). For example, the end-
of-sequence string <|endoftext|> should always be preserved as a single token (i.e., a single integer ID),
so we know when to stop generating from the language model. These special tokens must be added to the
vocabulary, so they have a corresponding fixed token ID.
Algorithm 1 of R. Sennrich et al. [3] contains an inefficient implementation of BPE tokenizer training
(essentially following the steps that we outlined above). As a first exercise, it may be useful to implement
and test this function to check your understanding.
Example (bpe_example): BPE training example
Here is a stylized example from R. Sennrich et al. [3]. Consider a corpus consisting of the
following text
low low low low low
lower lower widest widest widest
newest newest newest newest newest newest
and the vocabulary has a special token <|endoftext|>.
Vocabulary
We initialize our vocabulary with our special token <|endoftext|> and the 256 byte values.
Pre-tokenization
For simplicity and to focus on the merge procedure, we assume in this example that pre-
tokenization simply splits on whitespace. When we pre-tokenize and count, we end up with the
frequency table.
{low: 5, lower: 2, widest: 3, newest: 6}
It is convenient to represent this as a dict[tuple[bytes, ...], int], e.g. {(l,o,w): 5, …}. Note
that even a single byte is a bytes object in Python. There is no byte type in Python to represent
a single byte, just as there is no char type in Python to represent a single character.
Merges
We first look at every successive pair of bytes and sum the frequency of the words where they
appear {lo: 7, ow: 7, we: 8, er: 2, wi: 3, id: 3, de: 3, es: 9, st: 9, ne: 6, ew: 6}. The pairs ('e', 's')
and ('s', 't') are tied, so we take the lexicographically greater pair, ('s', 't'). We would then
merge the pre-tokens so that we end up with {(l,o,w): 5, (l,o,w,e,r): 2, (w,i,d,e,st): 3,
(n,e,w,e,st): 6}.
In the second round, we see that (e, st) is the most common pair (with a count of 9) and we
would merge into {(l,o,w): 5, (l,o,w,e,r): 2, (w,i,d,est): 3, (n,e,w,est): 6}. Continuing this,
the sequence of merges we get in the end will be ['s t', 'e st', 'o w', 'l ow', 'w est', 'n
e', 'ne west', 'w i', 'wi d', 'wid est', 'low e', 'lowe r'].
If we take 6 merges, we have ['s t', 'e st', 'o w', 'l ow', 'w est', 'n e'] and our
vocabulary elements would be [<|endoftext|>, [...256 BYTE CHARS], st, est, ow, low, west,
ne].
With this vocabulary and set of merges, the word newest would tokenize as [ne, west].
本章讨论
在 GitHub 查看记录 ↗