We can't find the internet
Attempting to reconnect
Something went wrong!
Attempting to reconnect
← Tokenization & Embeddings step 7 of 15
Subword Tokenizer: Greedy Longest-Prefix-Match
Split a string into vocabulary entries by repeatedly choosing the longest match at the current position. This is a simplified greedy subword tokenizer: it uses literal strings, without word splitting, continuation markers, normalization or unknown-token handling.
Your task
Implement subword_tokenize(text, vocab) with ordinary Python string and list
operations. Return a list[str] in text order, not token IDs or a tensor.
textis the string to split. Preserve its exact contents, including case, whitespace and punctuation.vocabis a list of token strings. It contains every individual character that appears intext, so at least one nonempty match always exists.
Starting at position 0:
- Find every vocabulary entry that matches the start of the remaining text.
- Choose the longest nonempty match and append it to the output.
- Advance by its length and repeat until no text remains.
Vocabulary order and duplicate entries do not affect the result. Empty
vocabulary entries, if present, are never emitted. An empty input string
returns []. Joining the returned tokens must reproduce text exactly.
Leave the supplied vocabulary list unchanged.
For text="cats" and vocab=["c", "a", "t", "s", "ca", "cat"], choose
"cat" first, then "s", giving ["cat", "s"].
Greedy does not mean fewest tokens
Do not backtrack or search for a globally shortest tokenization. For
text="abcdef" and a vocabulary containing each character plus "abc",
"abcd" and "def", return ["abcd", "e", "f"]. Choosing "abc" then
"def" would use fewer tokens, but would break the longest-match rule at
the first position.
To implement the search, try endpoints from the end of the text down toward the current position and stop at the first vocabulary match. A set makes membership checks convenient, but substring creation and the search still have a cost. This exercise does not implement vocabulary training or a full WordPiece tokenizer.
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.