We can't find the internet
Attempting to reconnect
Something went wrong!
Attempting to reconnect
← Tokenization & Embeddings step 3 of 15
BPE Encode Text
Encode text with a simplified, character-based BPE procedure. The merge rules and vocabulary are already supplied; you do not train a tokenizer.
Your task
Implement bpe_encode_text(text, vocab, merges) and return a Python list of
integer token IDs. Leave vocab and merges unchanged.
textis a Python string.mergesis an ordered list of two-string rules.vocabmaps token strings to integer IDs. It contains every token left after all merge passes. It need not contain characters that are completely merged away.
Follow these steps exactly:
- Start with
list(text), one token per Python character. - Visit each rule once in the supplied order. For that rule, scan the current tokens left to right and merge matching adjacent pairs without overlap. Use the resulting sequence as the input to the next rule.
- After the last rule, look up each remaining token in vocab and return its ID.
For text "lower" and rules
[["l", "o"], ["e", "r"], ["lo", "w"], ["low", "er"]]:
start: ["l", "o", "w", "e", "r"]
pass 1: ["lo", "w", "e", "r"]
pass 2: ["lo", "w", "er"]
pass 3: ["low", "er"]
pass 4: ["lower"]
If vocab maps "lower" to 6, return [6]. Intermediate tokens do not need
IDs because vocabulary lookup happens only after all passes.
Order and text handling
A rule that finds no match leaves the sequence unchanged. Do not restart the rule list when a later merge creates a token, and do not reorder rules by frequency or token length. Each pass has the same behavior as the BPE Merge Step exercise: newly merged output is not rescanned within that pass.
Treat spaces, punctuation and case literally. Do not split into words, strip
whitespace, normalize characters or convert the string to UTF-8 bytes. Python
characters are Unicode code points, which need not match visually perceived
characters. An empty string returns []; with no rules, look up the original
characters directly.
This exercise defines a small ordered-pass encoder. It does not reproduce a particular model's production tokenizer, which may use byte encoding, pre-tokenization and special tokens. Vocabulary IDs are supplied labels, not positions you assign from token order or length.
Understand the ideas behind this exercise. The Problem tab contains the exact implementation requirements.
Convert text into token IDs
A tokenizer decides which units of text the model sees. Whitespace splitting, greedy subword matching, and byte-pair encoding (BPE) use different rules. They can agree on one string and produce different results on another.
A greedy longest-prefix tokenizer chooses the longest vocabulary entry matching
the current position, emits its ID, then advances. With vocabulary a, ab,
and b, the text ab becomes one token. When no entry matches, handle the
unknown input and advance according to the task's rule. Otherwise the scan can
loop forever. A simplified exercise may omit WordPiece features such as
continuation markers and whole-word unknown handling.
Separate BPE training from encoding
BPE training learns merges by repeatedly combining frequent neighboring pairs. Encoding uses the learned merge order: apply eligible pairs according to their rank. It does not count frequencies afresh to learn a new tokenizer for each input. Follow the specified handling of overlapping pairs within a merge pass.
Pad a batch without treating padding as content
Sequences with lengths two and four can share a length-four tensor by adding two padding entries to the shorter sequence. An attention mask identifies which positions contain real tokens. Left and right padding place those tokens at different indices, which can affect position IDs and generation logic.
Keep the truncation length, unknown-token ID, and padding ID explicit. If the contract allows the padding ID to appear as real content, token values alone cannot identify padding; retain the lengths or mask. Return the list or tensor representation requested by the exercise.
Your code, saved here
Sign in to access your accepted solutions and saved draft history. You can keep reading the lesson without an account.
Sign in to your accountStuck?
PyTorch reference solution
Sign in to track your attempts toward unlocking the reference solution.