We can't find the internet
Attempting to reconnect
Something went wrong!
Attempting to reconnect
← Tokenization & Embeddings step 4 of 15
Tokenize and Pad Batch
Convert a list of strings into equally long lists of character IDs. Keep the start of each text if it is too long, and add padding on the right if it is shorter than the requested length.
Your task
Implement tokenize_and_pad_batch(texts, vocab, max_len, pad_id=-1) using
ordinary Python strings, dictionaries and lists. Return list[list[int]],
not a PyTorch tensor or JAX array.
textsis a list of strings. Preserve its order.vocabmaps individual characters to integer IDs. It contains every character in every input text, including characters beyond the cutoff.max_lenis a nonnegative integer specifying the length of every output row.pad_idis the integer to append for padding; its default is-1.
For each string, look up each character's ID, keep the first max_len IDs,
and append enough copies of pad_id to reach exactly max_len entries.
Use Python string iteration: spaces, punctuation and case matter. Do not
split into words, lowercase text, normalize Unicode or insert special tokens.
For texts=["ab", "a", "baba"], vocab={"a": 2, "b": 5}, max_len=3
and pad_id=-1, return:
[[2, 5, -1], [2, -1, -1], [5, 2, 5]]
An empty string produces a row of padding. An empty batch returns [].
If max_len=0, return one empty list per input text. Create separate output
rows and leave the input list and vocabulary unchanged.
Padding and model inputs
This function only builds ID lists. It does not return an attention mask.
Comparing an ID with pad_id identifies padding only when that ID is reserved
for padding and never represents a real character. If a real character has
the same ID, keep it; the function does not remove matching values.
The default -1 is a sentinel for this exercise, not a safe vocabulary index
to pass directly to an embedding lookup. A downstream model needs a valid
padding-token ID and suitable masking. Padding to a fixed length is the
batching convention used here, not a requirement for every model.
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?
JAX reference solution
Sign in to track your attempts toward unlocking the reference solution.