下列文本提取自本地原版 PDF。图表和公式的准确布局请对照 PDF。
2.5 Experimenting with BPE Tokenizer Training
Let’s train a byte-level BPE tokenizer on the TinyStories dataset. Instructions to find / download the
dataset can be found in Section 1. Before you start, we recommend taking a look at the TinyStories
dataset to get a sense of what’s in the data.
Parallelizing pre-tokenization
You will find that a major bottleneck is the pre-tokenization step. You can speed up pre-tokenization by
parallelizing your code with the built-in library multiprocessing. Concretely, we recommend that in
parallel implementations of pre-tokenization, you chunk the corpus while ensuring your chunk boundaries
occur at the beginning of a special token. You are free to use the starter code at the following link
verbatim to obtain chunk boundaries, which you can then use to distribute work across your processes:
https://github.com/stanford-cs336/assignment1-basics/blob/main/cs336_basics/pretokenization_example.py
This chunking will always be valid, since we never want to merge across document boundaries. For the
purposes of the assignment, you can always split in this way. Don’t worry about the edge case of receiving
a very large corpus that does not contain <|endoftext|>.
Removing special tokens before pre-tokenization
Before running pre-tokenization with the regex pattern (using re.finditer), you should strip out all
special tokens from your corpus (or your chunk, if using a parallel implementation). Make sure that you
split on your special tokens, so that no merging can occur across the text they delimit. For example, if
you have a corpus (or chunk) like [Doc 1]<|endoftext|>[Doc 2], you should split on the special token <|
endoftext|>, and pre-tokenize [Doc 1] and [Doc 2] separately, so that no merging can occur across the
document boundary. In other words, special tokens define hard segmentation boundaries during training,
but they should not themselves contribute to merge counts. This can be done using re.split with
"|".join(special_tokens) as the delimiter (with careful use of re.escape since | may occur in the special
tokens). The test test_train_bpe_special_tokens will test for this.
Optimizing the merging step
The naïve implementation of BPE training in the stylized example above is slow because for every merge,
it iterates over all byte pairs to identify the most frequent pair. However, the only pair counts that change
after each merge are those that overlap with the merged pair. Thus, BPE training speed can be improved
by indexing the counts of all pairs and incrementally updating these counts, rather than explicitly
iterating over each pair of bytes to count pair frequencies. You can get significant speedups with this
caching procedure, though we note that the merging part of BPE training is not parallelizable in Python.
Low-Resource Tip: Profiling
You should use profiling tools like cProfile or py-spy to identify the bottlenecks in your
implementation, and focus on optimizing those.
Low-Resource Tip: "Downscaling"
Instead of jumping to training your tokenizer on the full TinyStories dataset, we recommend you
first train on a small subset of the data: a “debug dataset”. For example, you could train your
tokenizer on the TinyStories validation set instead, which is 22K documents instead of 2.12M.
This illustrates a general strategy of downscaling whenever possible to speed up development: for
example, using smaller datasets, smaller model sizes, etc. Choosing the size of the debug dataset
or hyperparameter config requires careful consideration: you want your debug set to be large
enough to have the same bottlenecks as the full configuration (so that the optimizations you make
will generalize), but not so big that it takes forever to run.
Problem (train_bpe): BPE Tokenizer Training (15 points)
Deliverable: Write a function that, given a path to an input text file, trains a (byte-level) BPE
tokenizer. Your BPE training function should handle (at least) the following input parameters:
Input
input_path: str Path to a text file with BPE tokenizer training data.
vocab_size: int A positive integer that defines the maximum final vocabulary size (including
the initial byte vocabulary, vocabulary items produced from merging, and any special tokens).
special_tokens: list[str] A list of strings to add to the vocabulary. During training, treat
them as hard boundaries that prevent merges across their spans, but do not include them when
computing merge statistics.
Your BPE training function should return the resulting vocabulary and merges:
Output
vocab: dict[int, bytes] The tokenizer vocabulary, a mapping from int (token ID in the
vocabulary) to bytes (token bytes).
merges: list[tuple[bytes, bytes]] A list of BPE merges produced from training. Each list
item is a tuple of bytes (<token1>, <token2>), representing that <token1> was merged with
<token2>. The merges should be ordered by order of creation.
To test your BPE training function against our provided tests, you will first need to implement
the test adapter at [adapters.run_train_bpe] . Then, run uv run pytest tests/
test_train_bpe.py. Your implementation should be able to pass all tests. Optionally (this could
be a large time-investment), you can implement the key parts of your training method using some
systems language, for instance C++ (consider cppyy or nanobind) or Rust (using PyO3). If you do
this, be aware of which operations require copying vs reading directly from Python memory, and
make sure to leave build instructions, or make sure it builds using only pyproject.toml. Also note
that the GPT-2 regex is not well-supported in most regex engines and will be too slow in most
that do. We have verified that Oniguruma is reasonably fast and supports negative lookahead, but
the regex package in Python is, if anything, even faster.
Problem (train_bpe_tinystories): BPE Training on TinyStories (2 points)
(a) Train a byte-level BPE tokenizer on the TinyStories dataset, using a maximum vocabulary
size of 10,000. Make sure to add the TinyStories <|endoftext|> special token to the
vocabulary. Serialize the resulting vocabulary and merges to disk for further inspection. How
much time and memory did training take? What is the longest token in the vocabulary? Does
it make sense?
Resource requirements: ≤ 30 minutes (no GPUs), ≤ 30 GB RAM
Hint You should be able to get under 2 minutes for BPE training using multiprocessing
during pre-tokenization and the following two facts:
(a) The <|endoftext|> token delimits documents in the data files.
(b) The <|endoftext|> token is handled as a special case before the BPE merges are applied.
Deliverable: A one-to-two sentence response.
(b) Profile your code. What part of the tokenizer training process takes the most time?
Deliverable: A one-to-two sentence response.
Next, we’ll try training a byte-level BPE tokenizer on the OpenWebText dataset. As before, we
recommend taking a look at the dataset to better understand its contents.
Problem (train_bpe_expts_owt): BPE Training on OpenWebText (2 points)
(a) Train a byte-level BPE tokenizer on the OpenWebText dataset, using a maximum vocabulary
size of 32,000. Serialize the resulting vocabulary and merges to disk for further inspection.
What is the longest token in the vocabulary? Does it make sense?
Resource requirements: ≤ 12 hours (no GPUs), ≤ 100 GB RAM
Deliverable: A one-to-two sentence response.
(b) Compare and contrast the tokenizer that you get training on TinyStories versus
OpenWebText.
Deliverable: A one-to-two sentence response.
本章讨论
在 GitHub 查看记录 ↗