Lab 2 of 5about 30 minutes
A tiny tokenizer
It uses what you learned in Dicts and functions and Classes, just enough.
1A vocabulary
Run itFrom Dicts and functions
A language model reads numbers, not words. GPT-2's vocabulary is a dict of 50,257 keys. Yours has six. Run the cell: split cuts the sentence into its words.
2One word's number
Your turnFrom Dicts and functions
Write encode: it takes one word and gives back its number from vocab.
Hint
A dict finds a value by its key, in square brackets.
One way to do it
def encode(word):
return vocab[word]
encode("mat")3The whole sentence
Your turnFrom Dicts and functions
Now every word at once. Make ids, the list of each word's number, in one line.
Hint
Read a comprehension from its for: for each word in words, make what goes first.
One way to do it
ids = [encode(word) for word in words]
ids4A word it does not know
Your turnFrom Dicts and functions
Try encode("bird"). Python stops: KeyError: 'bird'. The dict holds no key 'bird'. Write encode again, so a word it does not know gets 6, one past the vocabulary's last number.
Hint
get comes with every dict. Its second input is what it gives back when the key is not there.
One way to do it
def encode(word):
return vocab.get(word, 6)
[encode(word) for word in "the bird sat".split()]5A tokenizer of its own
Your turnFrom Dicts and functions and Classes, just enough
Real tokenizers are objects: each keeps its own vocabulary and its own number for a word it does not know. Fill in the method, so it reads both through self.
Hint
Inside a method, the object is self. Its vocabulary is self.vocab.
One way to do it
class Tokenizer:
def __init__(self, vocab, unknown):
self.vocab = vocab
self.unknown = unknown
def encode(self, text):
return [self.vocab.get(word, self.unknown) for word in text.split()]
tok = Tokenizer(vocab, 6)
tok.encode("the dog sat on the mat")6Back to words
On your ownFrom Dicts and functions
Now the other way. Here is the vocabulary turned around, from each number to its word. Write a function decode: it takes a list of numbers and gives back the list of words.
words_of = {0: "the", 1: "cat", 2: "dog", 3: "sat", 4: "on", 5: "mat"}
Hint
It is encode's comprehension, the other way round: for each number, look its word up in words_of.
One way to do it
words_of = {0: "the", 1: "cat", 2: "dog", 3: "sat", 4: "on", 5: "mat"}
def decode(ids):
return [words_of[n] for n in ids]
decode([0, 2, 3, 4, 0, 5])Run on Pyodide 314, Python 3.14. Checked on .
