下列文本提取自本地原版 PDF。图表和公式的准确布局请对照 PDF。
2.6 BPE Tokenizer: Encoding and Decoding
In the previous part of the assignment, we implemented a function to train a BPE tokenizer on input text
to obtain a tokenizer vocabulary and a list of BPE merges. Now, we will implement a BPE tokenizer that
loads a provided vocabulary and list of merges and uses them to encode and decode text to/from token
IDs.
2.6.1 Encoding text
The process of encoding text by BPE mirrors how we train the BPE vocabulary. There are a few major
steps.
Step 1: Pre-tokenize. We first pre-tokenize the sequence and represent each pre-token as a sequence of
UTF-8 bytes, just as we did in BPE training. We will be merging these bytes within each pre-token into
vocabulary elements, handling each pre-token independently (no merges across pre-token boundaries).
Step 2: Apply the merges. We then take the sequence of vocabulary element merges created during
BPE training, and apply it to our pre-tokens in the same order of creation.
Example (bpe_encoding): BPE encoding example
For example, suppose our input string is 'the cat ate', our vocabulary is {0: b' ', 1: b'a', 2:
b'c', 3: b'e', 4: b'h', 5: b't', 6: b'th', 7: b' c', 8: b' a', 9: b'the', 10: b' at'}, and
our learned merges are [(b't', b'h'), (b' ', b'c'), (b' ', b'a'), (b'th', b'e'), (b' a',
b't')]. First, our pre-tokenizer would split this string into ['the', ' cat', ' ate']. Then, we’ll
look at each pre-token and apply the BPE merges.
The first pre-token 'the' is initially represented as [b't', b'h', b'e']. Looking at our list of
merges, we identify the first applicable merge to be (b't', b'h'), and use that to transform the
pre-token into [b'th', b'e']. Then, we go back to the list of merges and identify the next
applicable merge to be (b'th', b'e'), which transforms the pre-token into [b'the']. Finally,
looking back at the list of merges, we see that there are no more that apply to the string (since
the entire pre-token has been merged into a single token), so we are done applying the BPE
merges. The corresponding integer sequence is [9].
Repeating this process for the remaining pre-tokens, we see that the pre-token ' cat' is
represented as [b' c', b'a', b't'] after applying the BPE merges, which becomes the integer
sequence [7, 1, 5]. The final pre-token ' ate' is [b' at', b'e'] after applying the BPE merges,
which becomes the integer sequence [10, 3]. Thus, the final result of encoding our input string is
[9, 7, 1, 5, 10, 3].
Special tokens
Your tokenizer should be able to properly handle user-defined special tokens when encoding text
(provided when constructing the tokenizer).
Memory considerations
Suppose we want to tokenize a large text file that we cannot fit in memory. To efficiently tokenize this
large file (or any other stream of data), we need to break it up into manageable chunks and process each
chunk in turn, so that the memory complexity is constant as opposed to linear in the size of the text. In
doing so, we need to make sure that a token doesn’t cross chunk boundaries, else we’ll get a different
tokenization than the naïve method of tokenizing the entire sequence in-memory.
2.6.2 Decoding text
To decode a sequence of integer token IDs back to raw text, we can simply look up each ID’s
corresponding entries in the vocabulary (a byte sequence), concatenate them together, and then decode
the bytes to a Unicode string. Note that input IDs are not guaranteed to map to valid Unicode strings
(since a user could input any sequence of integer IDs). In the case that the input token IDs do not
produce a valid Unicode string, you should replace the malformed bytes with the official Unicode
replacement character U+FFFD.3 The errors argument of bytes.decode controls how Unicode decoding
errors are handled, and using errors='replace' will automatically replace malformed data with the
replacement marker.
Problem (tokenizer): Implementing the tokenizer (15 points)
Deliverable: Implement a Tokenizer class that, given a vocabulary and a list of merges, encodes
text into integer IDs and decodes integer IDs into text. Your tokenizer should also support user-
provided special tokens (appending them to the vocabulary if they aren’t already there). We
recommend the following interface:
3
See en.wikipedia.org/wiki/Specials_(Unicode_block)#Replacement_character for more information about the Unicode
replacement character.
def __init__(self, vocab, merges, special_tokens=None) Construct a tokenizer from a given
vocabulary, list of merges, and (optionally) a list of special tokens. This function should accept
the following parameters:
vocab: dict[int, bytes]
merges: list[tuple[bytes, bytes]]
special_tokens: list[str] | None = None
def from_files(cls, vocab_filepath, merges_filepath, special_tokens=None) Class method
that constructs and returns a Tokenizer from a serialized vocabulary and list of merges (in the
same format that your BPE training code output) and (optionally) a list of special tokens.
This method should accept the following additional parameters:
vocab_filepath: str
merges_filepath: str
special_tokens: list[str] | None = None
def encode(self, text: str) -> list[int] Encode an input text into a sequence of token IDs.
def encode_iterable(self, iterable: Iterable[str]) -> Iterator[int] Given an iterable of
strings (e.g., a Python file handle), return a generator that lazily yields token IDs. This is
required for memory-efficient tokenization of large files that we cannot directly load into
memory.
def decode(self, ids: list[int]) -> str Decode a sequence of token IDs into text.
To test your Tokenizer against our provided tests, you will first need to implement the test
adapter at [adapters.get_tokenizer] . Then, run uv run pytest tests/test_tokenizer.py. Your
implementation should be able to pass all tests.
2.7 Experiments
Problem (tokenizer_experiments): Experiments with tokenizers (4 points)
(a) Sample 10 documents from TinyStories and OpenWebText. Using your previously-trained
TinyStories and OpenWebText tokenizers (10K and 32K vocabulary size, respectively),
encode these sampled documents into integer IDs. What is each tokenizer’s compression ratio
(bytes/token)?
Deliverable: A one-to-two sentence response.
(b) What happens if you tokenize your OpenWebText sample with the TinyStories tokenizer?
Compare the compression ratio and/or qualitatively describe what happens.
Deliverable: A one-to-two sentence response.
(c) Estimate the throughput of your tokenizer (e.g., in bytes/second). How long would it take to
tokenize the Pile dataset (825GB of text)?
Deliverable: A one-to-two sentence response.
(d) Using your TinyStories and OpenWebText tokenizers, encode the respective training and
development datasets into a sequence of integer token IDs. We’ll use this later to train our
language model. We recommend serializing the token IDs as a NumPy array of datatype
uint16. Why is uint16 an appropriate choice?
Deliverable: A one-to-two sentence response.
本章讨论
在 GitHub 查看记录 ↗