02 · Vocabulary, token IDs, and embeddings¶
About 10–15 minutes · independent of unit 01
A language model reads its input along raw text → token IDs → embedding vector. This notebook isolates the last two arrows. An ID is a label used for lookup; an embedding is a vector associated with that label.
You will be able to: inspect a vocabulary in both directions; reconstruct text from token bytes; look up vectors without interpreting token IDs as meaningful numerical quantities.
1 · A tiny vocabulary you can inspect¶
This is a deliberately small lookup example, not a complete tokenizer or a 256-byte vocabulary. Its token IDs are invented. The keys label entries; the values are byte strings of different lengths.
Predict: do all four entries represent the same number of bytes?
Python: b"..." is a bytes literal. dict.items() yields (key, value) pairs; {k: v for ...} is a dictionary comprehension.
id_to_bytes = {0: b"h", 1: b"i", 2: b"hi", 3: b" hi"}
bytes_to_id = {piece: token_id for token_id, piece in id_to_bytes.items()}
for token_id, piece in id_to_bytes.items():
print("ID:", token_id, "bytes:", repr(piece), "byte length:", len(piece))
assert bytes_to_id[b"hi"] == 2
ID: 0 bytes: b'h' byte length: 1 ID: 1 bytes: b'i' byte length: 1 ID: 2 bytes: b'hi' byte length: 2 ID: 3 bytes: b' hi' byte length: 3
2 · Reconstruct text from a chosen sequence¶
We supply the sequence explicitly to focus on lookup. Choosing which pieces an encoder emits is a separate problem.
b"".join(...) concatenates byte strings. Decode the combined bytes as UTF-8, rather than assuming each token must contain a complete character.
token_ids = [2, 3]
pieces = [id_to_bytes[token_id] for token_id in token_ids]
restored_bytes = b"".join(pieces)
print("IDs:", token_ids)
print("Pieces:", pieces)
print("Text:", repr(restored_bytes.decode("utf-8")))
assert restored_bytes == b"hi hi"
IDs: [2, 3] Pieces: [b'hi', b' hi'] Text: 'hi hi'
3 · IDs label rows in an embedding table¶
Here each row has three made-up numbers. A real language model learns its embedding parameters during model training. This table is fixed demonstration data.
PyTorch indexing table[indices] selects the indicated rows. Predict: what shape will two token IDs produce?
import torch
embedding_table = torch.tensor([
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.2, 0.4, 0.6],
[0.8, 0.3, 0.1],
])
indices = torch.tensor(token_ids)
vectors = embedding_table[indices]
print("Table shape:", tuple(embedding_table.shape))
print("ID sequence shape:", tuple(indices.shape))
print("Selected vector shape:", tuple(vectors.shape))
print(vectors)
assert vectors.shape == (len(token_ids), 3)
Table shape: (4, 3)
ID sequence shape: (2,)
Selected vector shape: (2, 3)
tensor([[0.2000, 0.4000, 0.6000],
[0.8000, 0.3000, 0.1000]])
4 · Renaming IDs does not change the represented text¶
An ID being numerically close to another ID does not establish semantic similarity. If we consistently reorder both the vocabulary and embedding rows, lookup still yields the same text and vectors.
Inspect the mapping below: old ID 2 becomes new ID 0, for example.
Python: enumerate(seq) yields (index, value) pairs, starting at index 0.
new_to_old = [2, 0, 3, 1]
old_to_new = {old: new for new, old in enumerate(new_to_old)}
renamed_vocabulary = {new: id_to_bytes[old] for new, old in enumerate(new_to_old)}
renamed_table = embedding_table[new_to_old]
renamed_ids = [old_to_new[token_id] for token_id in token_ids]
print("Old IDs:", token_ids, "New IDs:", renamed_ids)
assert b"".join(renamed_vocabulary[i] for i in renamed_ids) == restored_bytes
torch.testing.assert_close(renamed_table[renamed_ids], vectors)
print("Same text and same selected vectors")
Old IDs: [2, 3] New IDs: [0, 2] Same text and same selected vectors
Your experiment¶
Change only my_ids to a different sequence of valid IDs. Predict the resulting text and vector shape. Repeating an ID repeats the same row at this lookup stage; contextual processing comes later.
my_ids = [0, 1, 3, 2]
print("Text:", repr(b"".join(id_to_bytes[i] for i in my_ids).decode("utf-8")))
print("Vectors:", embedding_table[my_ids])
assert embedding_table[my_ids].shape == (len(my_ids), 3)
Text: 'hi hihi'
Vectors: tensor([[1.0000, 0.0000, 0.0000],
[0.0000, 1.0000, 0.0000],
[0.8000, 0.3000, 0.1000],
[0.2000, 0.4000, 0.6000]])
What you found¶
- My prediction and observation:
- What belongs to the tokenizer vocabulary:
- What belongs to the language model:
- Why token ID 257 says nothing about the size or content of its vector:
Toward the CS336 tokenizer: separate byte payloads, integer labels, and learned parameters. Debugging becomes easier when you print each representation independently.
Reference: PyTorch indexing.