3/29
Part 1 of 5 · From words to vectorsLearn and do

Every token becomes a vector

A token id is just a number, like 1 for cat. The model needs a vector of C numbers to work with. nn.Embedding(V, C) is a table with one row per word, and looking a token up means reading its row:

# the cat sat on the mat
idx = torch.tensor([[0, 1, 2, 3, 0, 4]])
torch.manual_seed(0)
# V = 5 words, C = 3 numbers each
tok_emb = nn.Embedding(5, 3)
# one row per token
x = tok_emb(idx)
# (B, T, C)
print(x.shape)
# "the" at positions 0 and 4
print(torch.equal(x[0, 0], x[0, 4]))
torch.Size([1, 6, 3])
True

Six tokens in, six vectors out. the appears twice, at positions 0 and 4, so it gets the same row twice. The table is learned, like any other weight.

In the editor, idx holds the ids of the cat sat on the mat. Build tok_emb, a table with a row of 4 numbers for each of the 5 words. Then set x, the vectors for idx, and same, whether both copies of the got the same vector.